Spring OAuth2-更改默认签名算法 [英] Spring OAuth2 - Change default signing algorithm

查看:128
本文介绍了Spring OAuth2-更改默认签名算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Spring Security的新手,我需要在应用程序JWT身份验证中实施.因此,我在Spring网站上通过OAuth2指南编写了此代码.它工作正常,但默认情况下使用的是SHA256签名算法.您能告诉我如何将代码更改为使用SHA512或其他某种算法吗?谢谢.

I am new in Spring Security, I need implement in my application JWT authentication. So I made this code by OAuth2 guide on spring site. It is working nice, but by default is using SHA256 signing algorithm. Can you tell me how to change my code, to using SHA512, or some other algorithm? Thanks.

这是我的实现方式

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Value("${security.signing-key}")
    private String signingKey;

    @Value("${security.encoding-strength}")
    private Integer encodingStrength;

    @Value("${security.security-realm}")
    private String securityRealm;

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .httpBasic()
                .realmName(securityRealm)
                .and()
                .csrf()
                .disable();

    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(signingKey);
        return converter;
    }

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

    @Bean
    @Primary
    //Making this primary to avoid any accidental duplication with another token service instance of the same name
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }
}

授权服务器:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Value("${security.jwt.client-id}")
    private String clientId;

    @Value("${security.jwt.client-secret}")
    private String clientSecret;

    @Value("${security.jwt.grant-type}")
    private String grantType;

    @Value("${security.jwt.scope-read}")
    private String scopeRead;

    @Value("${security.jwt.scope-write}")
    private String scopeWrite = "write";

    @Value("${security.jwt.resource-ids}")
    private String resourceIds;

    @Value("${security.jwt.expiration}")
    private int expiration;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
        configurer
                .inMemory()
                .withClient(clientId)
                .secret(clientSecret)
                .authorizedGrantTypes(grantType)
                .scopes(scopeRead, scopeWrite)
                .resourceIds(resourceIds)
                .accessTokenValiditySeconds(expiration);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        endpoints.tokenStore(tokenStore)
                .accessTokenConverter(accessTokenConverter)
                .tokenEnhancer(enhancerChain)
                .authenticationManager(authenticationManager);
    }
}

资源服务器:

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private ResourceServerTokenServices tokenServices;

    @Value("${security.jwt.resource-ids}")
    private String resourceIds;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId(resourceIds).tokenServices(tokenServices);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .requestMatchers()
                .and()
                .authorizeRequests()
                .antMatchers("/actuator/**", "/api-docs/**").permitAll()
                .antMatchers("/springjwt/**" ).authenticated();
    }
}

推荐答案

从Spring Security OAuth2版本2.0.12开始,您可以设置签名者,请参见

Since version 2.0.12 of Spring Security OAuth2 you can set the signer, see Unable to configure the algorithm used for signing and verifying:

演示于2016年10月7日发表评论

desmondrawls commented on 7 Oct 2016

我们需要RsaSigner和RsaVerifier类使用sha512而不是sha256.因为JwtAccessTokenConverter使用默认算法sha256实例化了这些类,所以似乎配置该算法的唯一方法是在重写受软件包保护的RsaKeyHelper时扩展JwtAccessTokenConverter,RsaSigner和RsaVerifier.我们不想保留那么多的Spring安全类.我们还能怎么做呢?是否可以重写JwtAccessTokenConverter以便更轻松地配置算法?

We need the RsaSigner and RsaVerifier classes to use sha512 instead of sha256. Because the JwtAccessTokenConverter instantiates these classes with their default algorithm, sha256, it seems like the only way to configure the algorithm would be to extend the JwtAccessTokenConverter, RsaSigner, and RsaVerifier while rewriting the package-protected RsaKeyHelper. We don't want to maintain that many spring-security classes. How else could we do this? Could the JwtAccessTokenConverter be rewritten to allow easier configuration of the algorithm?

public void setVerifier(org.springframework.security.jwt.crypto.sign.SignatureVerifier verifier)

无条件设置验证者(然后将忽略Verifer键).

Unconditionally set the verifier (the verifer key is then ignored).

[...]

public void setSigner(org.springframework.security.jwt.crypto.sign.Signer signer)

无条件地设置要使用的签名者(如果需要).然后将忽略签名者密钥.

Unconditionally set the signer to use (if needed). The signer key is then ignored.

这篇关于Spring OAuth2-更改默认签名算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆