【问题标题】:Full authentication is required to access this resource with generated access token需要完全身份验证才能使用生成的访问令牌访问此资源
【发布时间】:2019-02-02 10:00:09
【问题描述】:

我正在尝试实现一个基本的授权服务器,所以在这里我已经在同一个应用程序项目下配置了 Auth Server 和 Resource Server。

认证服务器配置

@Configuration
@EnableAuthorizationServer
@EnableResourceServer
@ComponentScan("comm.sun.auth")
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private static String REALM="APP_REALM";
    private static final int ONE_DAY = 60 * 60 * 24;
    private static final int THIRTY_DAYS = 60 * 60 * 24 * 30;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("Client")
                .secret("Client_Secret")
                .authorizedGrantTypes("password", "refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                //.accessTokenValiditySeconds(ONE_DAY)
                .accessTokenValiditySeconds(3000)
                .refreshTokenValiditySeconds(THIRTY_DAYS);
    }

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

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM)
                .checkTokenAccess("isAuthenticated()");
    }

}

资源服务器配置

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //-- define URL patterns to enable OAuth2 security
        http.
                anonymous().disable()
                .requestMatchers().antMatchers("/api/**")
                .and().authorizeRequests()
                .antMatchers("/api/**")
                .access("hasRole('ADMIN') or hasRole('USER')")
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }
}

WebSecurity Config : /oauth/token enpoint 允许每个人使用

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ClientDetailsService clientDetailsService;

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("pass")
                .roles("ADMIN", "USER").and()
                .withUser("appuser")
                .password("pass123").roles("USER");
    }


    @Override
    @Order(Ordered.HIGHEST_PRECEDENCE)
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/about").permitAll()
                .antMatchers("/app/**").permitAll()
                .antMatchers("/oauth/token").permitAll()
//                .antMatchers("/api/**").permitAll()
                //.antMatchers("/api/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .httpBasic()
                .realmName("APP_REALM");
    }


    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public TokenStore tokenStore() {
        return new InMemoryTokenStore();
    }

    @Bean
    @Autowired
    public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore) {
        TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
        handler.setTokenStore(tokenStore);
        handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
        handler.setClientDetailsService(clientDetailsService);
        return handler;
    }

    @Bean
    @Autowired
    public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
        TokenApprovalStore store = new TokenApprovalStore();
        store.setTokenStore(tokenStore);
        return store;
    }


}

休息控制器

@RestController
public class apiControllers {

    @GetMapping( value = "/app/getclients")
    public ResponseEntity getAllClients(){
        return new ResponseEntity("All Clients", HttpStatus.OK);
    }

    @GetMapping( value = "/api/getusers")
    public ResponseEntity getAllUsers(){
        return new ResponseEntity("All Users", HttpStatus.OK);
    }


}

我的问题:使用/oauth/token 正在生成访问令牌,但是当我尝试使用生成的访问密钥Authorization : Bearer accesstoken 访问受保护的资源时,它给出了

"error": "Unauthorized",
"message": "Full authentication is required to access this resource"

可能有很多类似的问题,但大多数都与/oauth/token enpoint 有关。但在我的 senario /oauth/token enpoint 工作正常,但使用访问令牌我无法访问安全源。我看不出任何人都可以指导我找到解决方案的代码有任何问题。我使用 POSTMAN 测试端点并生成令牌

更新

build.gradle

version '1.0'

buildscript{
    ext{
        spring_boot_version = '1.5.2.RELEASE'
    }
    repositories{
        mavenCentral()
    }
    dependencies{
        classpath("org.springframework.boot:spring-boot-gradle-plugin:$spring_boot_version")
    }
}

task wrapper(type: Wrapper) {
    gradleVersion = '3.3'
    distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip"
}

apply plugin: 'java'
//apply plugin: 'war'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-rest', version: '1.5.4.RELEASE'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.5.6.RELEASE'
// https://mvnrepository.com/artifact/com.h2database/h2
    compile group: 'com.h2database', name: 'h2', version: '1.4.187'
    // https://mvnrepository.com/artifact/org.springframework.security.oauth/spring-security-oauth2
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-oauth2', version: '1.2.1.RELEASE'

}

【问题讨论】:

    标签: spring-boot authentication oauth-2.0 authorization spring-security-oauth2


    【解决方案1】:

    我觉得你这里有两个麻烦

    1. 有一个拼写错误@GetMapping( value = "/app/getclients") app 而不是 api。
    2. 可能您使用了错误的授权标头格式。

    我已经为您的问题创建了测试项目,一切都很好。请在此处查看https://github.com/alex-petrov81/stackoverflow-answers/tree/master/full-authentication-is-required-to-access-this-resource

    【讨论】:

    • 感谢您花时间研究这个问题,实际上正如您在项目中所说,它工作正常。我看到的唯一变化是构建文件。我使用了spring-cloud-starter-oauth2', version: '1.2.1.RELEASE' 我将在我的问题中更新构建 gradle 文件
    • 感谢build.gradle的分享。我已经更新了我的 GitHub 存储库,请检查 github.com/alex-petrov81/stackoverflow-answers/tree/master/… 看看那里的 WebSecurityConfig 和 @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 注释
    • @AlexanderPetrov - 你能帮帮我吗 - stackoverflow.com/questions/53090739/…
    【解决方案2】:

    我也遇到了这个错误。我通过在 application.properties 中写入以下内容来解决此问题

    security.oauth2.resource.filter-order=3
    

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 2020-03-30
      • 2018-06-12
      • 1970-01-01
      • 2016-10-03
      • 2018-06-29
      • 2017-06-30
      • 2016-11-11
      • 2015-01-08
      相关资源
      最近更新 更多