在使用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
求大神帮帮忙,谢谢
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。