开发者社区> 问答> 正文

Spring security oauth2——Could not obtain user details from token

在使用spring boot security oauth2搭建一个简单的授权服务器,创建了server,resource,client三个项目,代码如下
授权服务器:
@Configuration
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient("testclient")
            .secret("1234567890")
            .authorizedGrantTypes("authorization_code")
            .scopes("read");
}

}
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .antMatchers("/oauth/token").permitAll()
        .and()
        .formLogin()
        .and()
        .httpBasic()
        .and().csrf().disable();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("user").password("123").roles("USER");
}

}
资源服务器:
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests()
    .antMatchers("/user").hasRole("USER").anyRequest().authenticated().and().csrf().disable();
}

}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

}
@RestController
public class UserController {


@PreAuthorize("hasRole('ROLE_USER')")
@RequestMapping("/user")
public Map<String,String> user(Principal principal) {
    Map<String,String> map = new LinkedHashMap<>();
    map.put("name", principal.getName());
    return map;
}

}

客户端是使用@EnableOAuth2Sso注解创建,在浏览器访问客户端测试接口可以正常跳转到授权服务器登录和授权页面,但是授权之后报错:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Dec 20 15:04:25 CST 2017
There was an unexpected error (type=Unauthorized, status=401).
Authentication Failed: Could not obtain user details from token

后台DEBUG信息如下:
客户端:
2017-12-20 15:04:24.656 DEBUG 6896 --- [nio-8082-exec-4] o.s.s.oauth2.client.OAuth2RestTemplate : Created GET request for "http://localhost:8081/resource/user"
2017-12-20 15:04:24.679 DEBUG 6896 --- [nio-8082-exec-4] o.s.s.oauth2.client.OAuth2RestTemplate : Setting request Accept header to [application/json, application/*+json]
2017-12-20 15:04:24.995 DEBUG 6896 --- [nio-8082-exec-4] o.s.s.oauth2.client.OAuth2RestTemplate : GET request for "http://localhost:8081/resource/user" resulted in 401 (null); invoking error handler
2017-12-20 15:04:25.007 WARN 6896 --- [nio-8082-exec-4] o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class org.springframework.security.oauth2.common.exceptions.InvalidRequestException, Possible CSRF detected - state parameter was required but no state could be found
2017-12-20 15:04:25.014 DEBUG 6896 --- [nio-8082-exec-4] uth2ClientAuthenticationProcessingFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Could not obtain user details from token

org.springframework.security.authentication.BadCredentialsException: Could not obtain user details from token

授权服务器:
2017-12-20 15:04:14.570 DEBUG 9060 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/authorize?client_id=testclient&redirect_uri=http://localhost:8082/client/login&response_type=code&state=4ST5mq; Attributes: [authenticated]
2017-12-20 15:04:14.570 DEBUG 9060 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2017-12-20 15:04:14.577 DEBUG 9060 --- [nio-8080-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@79d73804, returned: -1
2017-12-20 15:04:14.586 DEBUG 9060 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied

资源服务器:
2017-12-20 15:04:24.883 DEBUG 7140 --- [nio-8081-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /user' doesn't match 'DELETE /logout
2017-12-20 15:04:24.883 DEBUG 7140 --- [nio-8081-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2017-12-20 15:04:24.884 DEBUG 7140 --- [nio-8081-exec-2] o.s.security.web.FilterChainProxy : /user at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2017-12-20 15:04:24.907 DEBUG 7140 --- [nio-8081-exec-2] p.a.OAuth2AuthenticationProcessingFilter : Authentication request failed: error="invalid_token", error_description="Invalid access token: 3269eae1-2862-476b-9324-a244c70dacc4"
2017-12-20 15:04:24.981 DEBUG 7140 --- [nio-8081-exec-2] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2017-12-20 15:04:24.999 DEBUG 7140 --- [nio-8081-exec-2] s.s.o.p.e.DefaultOAuth2ExceptionRenderer : Written [error="invalid_token", error_description="Invalid access token: 3269eae1-2862-476b-9324-a244c70dacc4"] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@76f66114]
2017-12-20 15:04:24.999 DEBUG 7140 --- [nio-8081-exec-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

求大神帮帮忙,谢谢

展开
收起
zuoyc 2017-12-20 15:47:09 12325 0
2 条回答
写回答
取消 提交回答
  • 2、表示我也想知道

    2019-07-17 21:49:49
    赞同 展开评论 打赏
  • 一个热爱科技,热爱生活的阳光男孩

    1,表示也想知道

    2019-07-17 21:49:48
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
云栖社区特邀专家徐雷Java Spring Boot开发实战系列课程(第20讲):经典面试题与阿里等名企内部招聘求职面试技巧 立即下载
微服务架构模式与原理Spring Cloud开发实战 立即下载
阿里特邀专家徐雷Java Spring Boot开发实战系列课程(第18讲):制作Java Docker镜像与推送到DockerHub和阿里云Docker仓库 立即下载

相关实验场景

更多