oauth2之JwtTokenStore返回jwt格式token
基于spring boot 2.0.4.RELEASE
加入依赖
compile('org.springframework.security:spring-security-jwt')
授权服务器配置
@Configuration
@EnableAuthorizationServer
//@EnableAuthorizationServer的作用就是添加一条拦截规则(这里是Oauth2)
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(){
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
//对称类型key
converter.setSigningKey("123456");
return converter;
}
@Bean
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
//设置jwtAccessTokenConverter,因为jwtAccessTokenConverter实现了TokenEnhancer接口
defaultTokenServices.setTokenEnhancer(jwtAccessTokenConverter());
defaultTokenServices.setClientDetailsService(clientDetailsService());
return defaultTokenServices;
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.realm("simple")
//exposes public key for token verification if using JWT tokens
//使用标准的spel语言就行
//默认都是denyAll()
.tokenKeyAccess("permitAll()")
//used by Resource Servers to decode access tokens
//jwt校验
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
}
资源服务器配置
@Configuration
@EnableResourceServer
public class ResourcesServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private ResourceServerTokenServices tokenServices;
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("product_api").stateless(false);
}
//omitted...
}
获取token
http://localhost:8080/oauth/token?grant_type=authorization_code&code=gJjkG8&client_id=pair&client_secret=secret&redirect_uri=http://baidu.com
:
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicHJvZHVjdF9hcGkiXSwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiLCJ0cnVzdCJdLCJleHAiOjE1MzYxMzA3OTgsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiNTFjMWJkNDctODUxZC00NTMyLWIwODItYTlhOTJiMDNiMTNhIiwiY2xpZW50X2lkIjoicGFpciJ9.CU2qTESn2fTq6YSJtWwDEcnZriVGJt1sPIZhOYr7_wI",
"token_type": "bearer",
"refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicHJvZHVjdF9hcGkiXSwidXNlcl9uYW1lIjoiYWRtaW4iLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiLCJ0cnVzdCJdLCJhdGkiOiI1MWMxYmQ0Ny04NTFkLTQ1MzItYjA4Mi1hOWE5MmIwM2IxM2EiLCJleHAiOjE1Mzg3MjA3OTgsImF1dGhvcml0aWVzIjpbIlJPTEVfQURNSU4iXSwianRpIjoiYTI2ODI4MTgtYWJjMS00NWJkLTgwNDEtN2NmZGEwZmI1YTMzIiwiY2xpZW50X2lkIjoicGFpciJ9.geQYgeoGEaqLqKYtU-ts4IRc0zqwZqclLJILsHi6TGM",
"expires_in": 1998,
"scope": "read write trust",
"jti": "51c1bd47-851d-4532-b082-a9a92b03b13a"
}