我使用spring-security-oauth实现了Oauth2。我使用了密码和刷新令牌授权类型。
流程是用户首先显示用户名和密码,验证后,授权服务器提供刷新令牌。 使用该刷新令牌,我获得了可用于访问受保护资源的访问令牌。
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter implements EnvironmentAware {
private static final String ENV_OAUTH = "authentication.oauth.";
private static final String PROP_CLIENTID = "clientid";
private static final String PROP_SECRET = "secret";
private static final String PROP_TOKEN_VALIDITY_SECONDS = "tokenValidityInSeconds";
private RelaxedPropertyResolver propertyResolver;
@Autowired
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(propertyResolver.getProperty(PROP_CLIENTID))
.scopes("read", "write")
.authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name())
.authorizedGrantTypes("password", "refresh_token")
.secret(propertyResolver.getProperty(PROP_SECRET))
.accessTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 60))
.refreshTokenValiditySeconds(propertyResolver.getProperty(PROP_TOKEN_VALIDITY_SECONDS, Integer.class, 120));
}
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment, ENV_OAUTH);
}
}
}
注意:我使用过JdbcTokenStore
,请检查上面的代码。
每当创建/删除新的访问令牌时,我想执行一个方法并希望运行一些代码。这该怎么做?我是春天安全和oauth的新手,请建议我实现这一目标的方法。我可以为此添加任何过滤器或拦截器吗?
答案 0 :(得分:5)
您可以实施自己的TokenStore或扩展现有的InMemoryTokenStore,
JdbcTokenStore
,JwtTokenStore
)并在storeAccessToken
和{{1}中添加您的代码}