Spring security oauth2——Could not obtain user details from token-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

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

2017-12-20 15:47:09 10142 2

在使用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

求大神帮帮忙,谢谢

取消 提交回答
全部回答(2)
  • 急速涡轮
    2019-07-17 21:49:49

    2、表示我也想知道

    0 0
  • 孤狼:
    2019-07-17 21:49:48

    1,表示也想知道

    0 0
添加回答
相关问答

162

回答

惊喜翻倍:免费ECS+免费环境配置~!(ECS免费体验6个月活动3月31日结束)

豆妹 2014-10-29 17:52:21 226087浏览量 回答数 162

8

回答

OceanBase 使用动画(持续更新)

mq4096 2019-02-20 17:16:36 336969浏览量 回答数 8

110

回答

OSS存储服务-客户端工具

newegg11 2012-05-17 15:37:18 295465浏览量 回答数 110

22

回答

爬虫数据管理【问答合集】

我是管理员 2018-08-10 16:37:41 147213浏览量 回答数 22

18

回答

阿里云开放端口权限

xcxx 2016-07-20 15:03:33 646716浏览量 回答数 18

33

回答

Win Server 2003-2016 加密勒索事件必打补丁合集

妙正灰 2017-05-15 10:44:38 280357浏览量 回答数 33

38

回答

安全组详解,新手必看教程

我的中国 2017-11-30 15:23:46 259794浏览量 回答数 38

294

回答

Linux Bash严重漏洞修复紧急通知(已全部给出最终修复方案)

qilu 2014-09-25 13:26:50 434527浏览量 回答数 294

24

回答

【精品问答】python技术1000问(1)

问问小秘 2019-11-15 13:25:00 475463浏览量 回答数 24

13

回答

游戏云精彩帖汇总

nono20011908 2014-08-22 11:00:12 203950浏览量 回答数 13
+关注
0
文章
3
问答
问答排行榜
最热
最新
相关电子书
更多
《Nacos架构&原理》
立即下载
《看见新力量:二》电子书
立即下载
云上自动化运维(CloudOps)白皮书
立即下载