Spring security 如何在Spring Security中配置资源服务器,使其使用JWT令牌中的附加信息

Spring security 如何在Spring Security中配置资源服务器,使其使用JWT令牌中的附加信息,spring-security,jwt,spring-security-oauth2,Spring Security,Jwt,Spring Security Oauth2,我有一个oauth2 jwt令牌服务器,用于设置有关用户权限的其他信息 @Configuration @Component public class CustomTokenEnhancer extends JwtAccessTokenConverter { CustomTokenEnhancer(){ super(); } @Override public OAuth2AccessToken enhance(OAuth2AccessToken

我有一个oauth2 jwt令牌服务器,用于设置有关用户权限的其他信息

@Configuration
@Component
public class CustomTokenEnhancer extends JwtAccessTokenConverter {

    CustomTokenEnhancer(){
        super();
    }

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        // TODO Auto-generated method stub
        MyUserDetails user = (MyUserDetails) authentication.getPrincipal();
        final Map<String, Object> additionalInfo = new HashMap<>();
        @SuppressWarnings("unchecked")
        List<GrantedAuthority> authorities= (List<GrantedAuthority>) user.getAuthorities();
        additionalInfo.put("authorities", authorities);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }

}
我的资源服务器配置如下所示:

@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Value("${config.oauth2.privateKey}")
    private String privateKey;

    @Value("${config.oauth2.publicKey}")
    private String publicKey;

    @Value("{config.clienturl}")
    private String clientUrl;

    @Autowired
    AuthenticationManager authenticationManager;

    @Bean
    public JwtAccessTokenConverter customTokenEnhancer(){

        JwtAccessTokenConverter customTokenEnhancer = new CustomTokenEnhancer();
        customTokenEnhancer.setSigningKey(privateKey);

        return customTokenEnhancer;
    }

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


    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("isAnonymous() || hasRole('ROLE_TRUSTED_CLIENT')") // permitAll()
                .checkTokenAccess("hasRole('TRUSTED_CLIENT')"); // isAuthenticated()
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints


        .authenticationManager(authenticationManager)
        .tokenStore(tokenStore())
        .accessTokenConverter(customTokenEnhancer())
;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        String url = clientUrl;

        clients.inMemory()


        .withClient("public") 
        .authorizedGrantTypes("client_credentials", "implicit")
        .scopes("read")
        .redirectUris(url)

        .and()


        .withClient("eagree_web").secret("eagree_web_dev")
        //eagree_web should come from properties file?
        .authorities("ROLE_TRUSTED_CLIENT") 
        .authorizedGrantTypes("client_credentials", "password", "authorization_code", "refresh_token")
        .scopes("read", "write", "trust") 
        .redirectUris(url).resourceIds("dummy");
    }
}
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration  extends ResourceServerConfigurerAdapter {



    @Value("{config.oauth2.publicKey}")
    private String publicKey;

    @Autowired
    CustomTokenEnhancer tokenConverter;

    @Autowired
    JwtTokenStore jwtTokenStore;

    @Bean
    public JwtTokenStore jwtTokenStore() {
        tokenConverter.setVerifierKey(publicKey);
        jwtTokenStore.setTokenEnhancer(tokenConverter);
        return jwtTokenStore;
    }

    @Bean
    public ResourceServerTokenServices defaultTokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenEnhancer(tokenConverter);
        defaultTokenServices.setTokenStore(jwtTokenStore());
        return defaultTokenServices;
    }


    @Override
    public void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        // @formatter:off
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
                .and()
                .requestMatchers()
                .antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll()
                .antMatchers(HttpMethod.GET, "/api/**").access("#oauth2.hasScope('read')")
                .antMatchers(HttpMethod.PATCH, "/api/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.POST, "/api/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.PUT, "/api/**").access("#oauth2.hasScope('write')")
                .antMatchers(HttpMethod.DELETE, "/api/**").access("#oauth2.hasScope('write')")
                .antMatchers("/admin/**").access("hasRole('ROLE_USER')");

        // @formatter:on
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        System.out.println("Configuring ResourceServerSecurityConfigurer ");
        resources.resourceId("dummy").tokenServices(defaultTokenServices());
    }

}
我的测试用例失败得很惨,它说:

{“error”:“invalid_token”,“error_description”:“Cannot convert access token to JSON”}

如何从JWT中获取身份验证对象? 如何使用客户端凭据对客户端进行身份验证? 如何在资源控制器上使用@Secured注释

资源服务器端使用什么代码按顺序解码令牌 提取客户端凭据以及验证用户角色的代码是什么

请帮帮我,因为我已经花了两天的时间在这上面敲打我的头了 简单的任务

注意:我从Auth server接收令牌的方式为: {access_token=b5d89a13-3c8b-4bda-b0f2-a6e9d7b7a285,token_type=bearer,refresh_token=43777224-b6f2-44d7-bf36-4e1934d32cbb,expires_in=43199,scope=读写信任,authority=[{authority=ROLE_USER},{authority=ROLE_ADMIN}]


请解释这些概念,并指出我的配置中是否缺少任何内容。我需要知道在配置我的资源和身份验证服务器方面的最佳实践。

在以下内容中,我指的是我已经成功实施的Baeldung教程:

首先:在AuthorizationServer端使用CustomTokenEnhancer,以使用其他自定义信息增强创建的令牌。您应该在ResourceServer端使用所谓的DefaultAccessTokenConverter来提取这些额外的声明

您可以
@Autowire
将CustomAccessTokenConverter设置到ResourceServerConfiguration类中,然后将其设置为
JwtTokenStore()
配置

资源服务器配置:

@Autowired
private CustomAccessTokenConverter yourCustomAccessTokenConverter;

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setAccessTokenConverter(yourCustomAccessTokenConverter);
    converter.setSigningKey(yourSigningKey);
    return converter;
}
@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
        OAuth2Authentication authentication = super.extractAuthentication(claims);
        authentication.setDetails(claims);
        return authentication;
    }

}
可以配置CustomAccessTokenConverter,以便在此处提取自定义声明

CustomAccessTokenConverter:

@Autowired
private CustomAccessTokenConverter yourCustomAccessTokenConverter;

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

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setAccessTokenConverter(yourCustomAccessTokenConverter);
    converter.setSigningKey(yourSigningKey);
    return converter;
}
@Component
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
        OAuth2Authentication authentication = super.extractAuthentication(claims);
        authentication.setDetails(claims);
        return authentication;
    }

}
@组件
公共类CustomAccessTokenConverter扩展了DefaultAccessTokenConverter{
@凌驾
公共OAuth2Authentication extractAuthentication(映射声明){
OAuth2AuthenticationAuthentication=super.extractAuthentication(声明);
认证。详细信息(声明);
返回认证;
}
}
(见:)