首页 > 解决方案 > 使用 oauth2 在 Spring Security 中使用 jwt 令牌时访问被拒绝

问题描述

我在访问基于角色的请求时被拒绝访问。我不知道为什么。我在spring boot中使用带有oauth2的spring security。

配置的授权服务器是 -

@EnableAuthorizationServer
@Configuration
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authManager;
    @Autowired
    private AuthConfig config;
    @Autowired
    private UserDetailsService userDetailsService;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient(config.getClientId()).secret("{noop}".concat(config.getClientSecret()))
                .scopes("read", "write").authorizedGrantTypes("password", "refresh_token")
                .accessTokenValiditySeconds(config.getAccessTokenValidity())
                .refreshTokenValiditySeconds(config.getRefresTokenValidity());
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.pathMapping("/oauth/token", config.getAuthPath());
        endpoints.authenticationManager(authManager).tokenStore(tokenStore()).accessTokenConverter(jwtTokenEnhancer());
        endpoints.userDetailsService(userDetailsService);
    }

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

    @Bean
    protected JwtAccessTokenConverter jwtTokenEnhancer() {
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"),
                config.getKeyStorePassword().toCharArray());
        JwtAccessTokenConverter converter = new CustomTokenEnhancer();
        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));
        return converter;
    }
}

并且资源服务器配置为

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String RESOURCE_ID = "my_rest_api";

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

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

}

并将服务器安全配置为

@Configuration
@EnableWebSecurity(debug = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

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

生成令牌中的解码数据是

{
  "exp": 1547123578,
  "user_name": "superadmin",
  "authorities": [
    {
      "authority": "ROLE_superadmin"
    }
  ],
  "jti": "e1f6e67c-16b8-4a12-a300-fae7f406359e",
  "client_id": "pgcil",
  "scope": [
    "read",
    "write"
  ]
}

但是带有 jwt 令牌的http 请求http://localhost:8089/hello会给出访问被拒绝错误。谁能告诉我我做错了什么。任何帮助将不胜感激。

标签: springspring-bootspring-securityoauth-2.0spring-security-oauth2

解决方案


推荐阅读