繁体   English   中英

Spring Boot 2.0.3 Oauth2安全性:即使在标头中使用访问令牌也会出现401错误

[英]Spring Boot 2.0.3 Oauth2 Security: Getting 401 error even when using access token in header

我正在创建一个spring boot 2.0应用程序并尝试启用oauth2安全性。 我在现在的应用程序中有Auth服务器和资源服务器。 我的客户端和用户详细信息以及生成的令牌都保存在数据库(mysql)中,数据库模式与spring文档提供的相同。 当我点击'/ oauth / token /'端点使用Postman在标题和用户凭证中提供clientId和clientSecret时,我成功获得了访问令牌。

{
"access_token": "bef2d974-2e7d-4bf0-849d-d80e8021dc50",
"token_type": "bearer",
"refresh_token": "32ed6252-e7ee-442c-b6f9-d83b0511fcff",
"expires_in": 6345,
"scope": "read write trust"
}

但是当我尝试使用此访问令牌打我的休息api时,我收到401 Unauthorized错误:

{
"timestamp": "2018-08-13T11:17:19.813+0000",
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/myapp/api/unsecure"
}

我正在尝试的其他API如下:

HTTP://本地主机:8080 / MyApp的/ API /不安全

HTTP://本地主机:8080 / MyApp的/ API /安全

myapp是我的应用程序的上下文路径。

对于'secure'api,我在请求标头中提供了访问令牌,如Spring文档中所述:

Authorization: Bearer bef2d974-2e7d-4bf0-849d-d80e8021dc50

对于不安全的api,我尝试过使用和不使用Authentication头。 在所有情况下,我都得到两个apis相同的错误。

此外,当我尝试打印当前经过身份验证的用户时,它将作为匿名用户打印。

我想要的是如下:

1)我希望只有在请求标头中提供访问令牌时才能访问我的安全api。

2)我希望未经授权的用户可以访问我的不安全API。

3)访问安全URL时,我应该使用SecurityContextHolder获取当前经过身份验证的用户。

我的WebSecurityConfigurerAdapter如下:

@Configuration
@EnableWebSecurity(debug=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
UserDetailsService userDetailsService;

@Autowired
private ClientDetailsService clientDetailsService;

@Bean
public PasswordEncoder userPasswordEncoder() {
    return new BCryptPasswordEncoder(8);
}

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

@Autowired
public void configure(AuthenticationManagerBuilder auth) throws 
Exception {
    auth
    .userDetailsService(userDetailsService)
    .passwordEncoder(userPasswordEncoder());
}

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

@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;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .cors().disable()
    .anonymous().disable()
    .authorizeRequests()
    .antMatchers("/index.html", "/**.js", "/**.css", "/").permitAll()
    .anyRequest().authenticated()
    .and()
    .httpBasic();
}

在这里使用antMatchers我已经允许Angular 6应用程序的静态页面,因为我打算在我的真实应用程序中使用它们。 不,以下行不允许角度应用的静态页面:

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

我的AuthorizationServerConfigurerAdapter如下:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends 
AuthorizationServerConfigurerAdapter {

@Autowired
private DataSource dataSource;

@Autowired
UserDetailsService userDetailsService;

@Autowired
PasswordEncoder passwordEncoder;

@Autowired
TokenStore tokenStore;

@Autowired
private UserApprovalHandler userApprovalHandler;

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


@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer
    .tokenKeyAccess("permitAll()")
    .checkTokenAccess("isAuthenticated()")
    .passwordEncoder(passwordEncoder);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.jdbc(dataSource);
}

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

我的ResourceServerConfigurerAdapter如下:

@Configuration
@EnableResourceServer
public abstract class ResourceServerConfig extends ResourceServerConfigurerAdapter {

private static final String RESOURCE_ID = "resource-server-rest-api";

@Autowired
TokenStore tokenStore;

@Override
public void configure(ResourceServerSecurityConfigurer resources) {
    resources
    .resourceId(RESOURCE_ID)
    .tokenStore(tokenStore);
}

@Override
public void configure(HttpSecurity http) throws Exception {

    http
    .csrf().disable()
    .cors().disable()
    .anonymous().disable()
    .requestMatchers()
    .antMatchers("/api/**").and()
    .authorizeRequests()
    .antMatchers("/api/secure").authenticated()
    .antMatchers("/api/unsecure").permitAll();
}
}

但是当我在SecurityConfig中启用匿名访问并将我的不安全URL声明为permitAll时,我就能访问该URL。

.antMatchers("/api/unsecure", "/index.html", "/**.js", "/**.css", "/").permitAll()

我的Controller类如下:

@RestController
@RequestMapping("/api")
public class DemoController {

@GetMapping("/secure")
public void sayHelloFriend() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    System.out.println("Current User: "+authentication.getName());
    System.out.println("Hello Friend");
}

@GetMapping("/unsecure")
public void sayHelloStranger() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    System.out.println("Current User: "+authentication.getName());
    System.out.println("Hello Stranger");
}
}

如果需要更多信息,请与我们联系。 任何帮助将不胜感激。 但请记住,它的Spring Boot 2.0不是1.5,因为根据我的发现,它们都有一些重要的区别。

尝试添加

@Order(SecurityProperties.BASIC_AUTH_ORDER)

对于securityConfig? 因此链将首先检查您的资源服务器的配置。

并且不确定您的类型错误是否从资源服务器中删除了摘要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM