问题
I would like to have better control of the "state" param used in OAuth2 with spring security.
DefaultStateKeyGenerator just returns a random 6 character string.
AuthorizationCodeAccessTokenProvider
has a setStateKeyGenerator
but I'm not sure how to get an instance to call the setter.
I find it strange that StateKeyGenerator
takes an OAuth2ProtectedResourceDetails
, but the default implementation just ignores it and there's no details on how to configure your own
~/repos/jtor > mvn dependency:tree | grep security
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:2.0.14.RELEASE:compile
[INFO] | +- org.springframework.security:spring-security-core:jar:4.2.3.RELEASE:compile
[INFO] | +- org.springframework.security:spring-security-config:jar:4.2.3.RELEASE:compile
[INFO] | +- org.springframework.security:spring-security-web:jar:4.2.3.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-jwt:jar:1.0.8.RELEASE:compile
[INFO] \- org.springframework.security:spring-security-test:jar:4.2.3.RELEASE:test
回答1:
Depending on your usage, you can implement your own StateKeyGenerator
then configure beans to use it. You're free to use the resource
if it's relevant to your use case but it's ok to ignore it!
Here is a possible configuration:
@Bean
public StateKeyGenerator stateKeyGenerator() {
return new CustomStateKeyGenerator();
}
@Bean
public AccessTokenProvider accessTokenProvider() {
AuthorizationCodeAccessTokenProvider accessTokenProvider = new AuthorizationCodeAccessTokenProvider();
accessTokenProvider.setStateKeyGenerator(stateKeyGenerator());
return accessTokenProvider;
}
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.INTERFACES)
public OAuth2RestTemplate restTemplate() {
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(myResource(), new DefaultOAuth2ClientContext(accessTokenRequest));
restTemplate.setAccessTokenProvider(accessTokenProvider());
return restTemplate;
}
来源:https://stackoverflow.com/questions/46062208/spring-security-statekeygenerator-custom-instance