Spring Boot + OAuth2:访问此资源需要完整的身份验证。

11

我正在尝试使用Spring Boot、Spring Cloud Security和Spring Cloud OAuth2实现一个认证服务器。

当我尝试从Postman访问 http://localhost:8080/auth/oauth/token 时,出现以下错误:

{ "error": "unauthorized", "error_description": "Full authentication is required to access this resource" }

以下是我的pom.xml文件。

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> . 
<modelVersion>4.0.0</modelVersion>
<groupId>com.teckink.tp</groupId>
<artifactId>tp-auth-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>tp-auth-server</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.M9</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
</project>

启动(主)类:

package com.teckink.tp.authserver;

import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
@EnableResourceServer
@EnableAuthorizationServer
public class App {
    @RequestMapping(value = { "/user" }, produces = "application/json")
    public Map<String, Object> user(OAuth2Authentication user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("user", user.getUserAuthentication().getPrincipal());
        userInfo.put("authorities", AuthorityUtils.authorityListToSet(user.getUserAuthentication().getAuthorities()));
        return userInfo;
    }


    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

OAuth2Config类定义客户端及其密钥:

package com.teckink.tp.authserver.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")
                .secret("thisissecret")
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
      endpoints
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
    }
}

WebSecurityConfigurer 类定义了内存中的用户、密码和角色:

package com.teckink.tp.authserver.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
        @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

   @Override
    @Bean
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return super.userDetailsServiceBean();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("john.carnell").password("password1").roles("USER")
                .and()
                .withUser("william.woodward").password("password2").roles("USER", "ADMIN");
    }
}

我正在使用POSTMAN调用Rest API,请求时会显示如下身份验证屏幕:enter image description here。请求表单数据如下:enter image description here

如果可能的话,请将可重现的示例项目上传到GitHub。 - Kyle Anderson
@Prithvi - 你认为你能帮我解决这个问题吗?- https://stackoverflow.com/questions/53090739/spring-boot-jwt-security-full-authentication-is-required - SK.
@KyleAnderson - 你能帮我解决这个问题吗?- https://stackoverflow.com/questions/53090739/spring-boot-jwt-security-full-authentication-is-required - SK.
5个回答

7

在您的示例应用程序运行时,您会收到以下异常:

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

在spring-security-core:5.0中,默认的PasswordEncoder被构建为DelegatingPasswordEncoder。因此,当您将用户存储在内存中时,您会提供明文密码,然后当您尝试从DelegatingPasswordEncoder检索编码器以验证密码时,它找不到。

更多详细信息请参见此链接Password Encoding

为了解决这个问题,对于生产实现,您应该激活一个BCryptPasswordEncoder实例

对于开发环境,您可以尝试进行以下更改,以便通过在密码值中添加{noop}来覆盖密码编码。这将激活NoOpPasswordEncoder而不是默认的DelegatingPasswordEncoder,并将您的密码视为明文。

OAuth2Config类

clients.inMemory()
            .withClient("eagleeye")
            .secret("{noop}thisissecret")
            .authorizedGrantTypes("refresh_token", "password", "client_credentials")
            .scopes("webclient", "mobileclient");

WebSecurityConfigurer类

 auth
                .inMemoryAuthentication()
                .withUser("john.carnell"). password("{noop}password1").roles("USER")
                .and()
                .withUser("william.woodward").password("{noop}password2").roles("USER", "ADMIN");

现在当你使用Postman尝试时,你将能够生成token。 输入图像描述 编辑 带有工作演示的Github项目在这里

我在控制台中没有收到任何错误信息。 同时,我在密码和秘钥前加上了{noop},但是在响应中仍然得到相同的错误提示:"需要完整的身份验证才能访问此资源"。 - Prithvipal Singh
已上传一个 GitHub 项目的链接。请查看与您正在使用的代码库有何不同。 - CGS
1
我一开始访问了错误的端点:http://localhost:8080/auth/oauth/token。我将其更改为http://localhost:8080/oauth/token,然后出现了您上面提到的错误。我通过在前缀中添加{noop}来解决该错误。 - Prithvipal Singh
@Chids - 你能帮我看一下这个问题吗?- https://stackoverflow.com/questions/53090739/spring-boot-jwt-security-full-authentication-is-required - SK.

4

我遇到了同样的问题。URL是错误的,请更改为http://localhost:8080/oauth/token,然后就可以了。 我从一本书中获取了这个示例,但它提供了错误的URL。只需删除“/auth”即可。


1
以下更改解决了我在阅读John Carnell的《Spring微服务实战》时遇到的问题。
更改了以下属性。

application.yml

server:
  contextPath: /auth

server:
  servlet:
    context-path: /auth

我也为每个密码/秘密添加了 {noop},现在它可以正常工作!

WebSecurityConfigurer.java

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("john.carnell").password("{noop}password1").roles("USER")
                .and()
                .withUser("william.woodward").password("{noop}password2").roles("USER", "ADMIN");
    }

OAuth2Config.java

@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("eagleeye")
                .secret("{noop}thisissecret")
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                .scopes("webclient", "mobileclient");
    }

我正在使用Spring Cloud Hoxton SR11。

0

这里也发生了同样奇怪的事情。我通过使用curl命令解决了它。

curl -v -X POST  http://url:8080/api/oauth/token -u "yourclientid:yourclient_secret"   -d "grant_type=password"   -d "username=yourusername" -d "password=yourpassword"

或者,如果你想在Postman中使用它,请前往Authorization --> 选择类型OAUTH2 --> 获取访问令牌输入图像描述


0

我注意到您在帖子中将授权类型列为“passwor”,而不是“password”

请您更正一下,再试一次好吗?


1
我把它改成了“密码”。仍然收到相同的错误。 - Prithvipal Singh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接