SpringBoot實戰電商項目mall(20k+star)地址: https://github.com/macrozheng/mall
Spring Cloud Security 爲構建安全的SpringBoot應用提供了一系列解決方案,結合Oauth2還能夠實現更多功能,好比使用JWT令牌存儲信息,刷新令牌功能,本文將對其結合JWT使用進行詳細介紹。java
JWT是JSON WEB TOKEN的縮寫,它是基於 RFC 7519 標準定義的一種能夠安全傳輸的的JSON對象,因爲使用了數字簽名,因此是可信任和安全的。
{ "alg": "HS256", "typ": "JWT" }
{ "exp": 1572682831, "user_name": "macro", "authorities": [ "admin" ], "jti": "c1a0645a-28b5-4468-b4c7-9623131853af", "client_id": "admin", "scope": [ "all" ] }
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzI2ODI4MzEsInVzZXJfbmFtZSI6Im1hY3JvIiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiYzFhMDY0NWEtMjhiNS00NDY4LWI0YzctOTYyMzEzMTg1M2FmIiwiY2xpZW50X2lkIjoiYWRtaW4iLCJzY29wZSI6WyJhbGwiXX0.x4i6sRN49R6JSjd5hd1Fr2DdEMBsYdC4KB6Uw1huXPg
該模塊只是對oauth2-server模塊的擴展,直接複製過來擴展下下便可。git
在上一節中咱們都是把令牌存儲在內存中的,這樣若是部署多個服務,就會致使沒法使用令牌的問題。
Spring Cloud Security中有兩種存儲令牌的方式可用於解決該問題,一種是使用Redis來存儲,另外一種是使用JWT來存儲。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
spring: redis: #redis相關配置 password: 123456 #有密碼時設置
/** * 使用redis存儲token的配置 * Created by macro on 2019/10/8. */ @Configuration public class RedisTokenStoreConfig { @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public TokenStore redisTokenStore (){ return new RedisTokenStore(redisConnectionFactory); } }
/** * 認證服務器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserService userService; @Autowired @Qualifier("redisTokenStore") private TokenStore tokenStore; /** * 使用密碼模式須要配置 */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints.authenticationManager(authenticationManager) .userDetailsService(userService) .tokenStore(tokenStore);//配置令牌存儲策略 } //省略代碼... }
/** * 使用Jwt存儲token的配置 * Created by macro on 2019/10/8. */ @Configuration public class JwtTokenStoreConfig { @Bean public TokenStore jwtTokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter(); accessTokenConverter.setSigningKey("test_key");//配置JWT使用的祕鑰 return accessTokenConverter; } }
/** * 認證服務器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserService userService; @Autowired @Qualifier("jwtTokenStore") private TokenStore tokenStore; @Autowired private JwtAccessTokenConverter jwtAccessTokenConverter; @Autowired private JwtTokenEnhancer jwtTokenEnhancer; /** * 使用密碼模式須要配置 */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints.authenticationManager(authenticationManager) .userDetailsService(userService) .tokenStore(tokenStore) //配置令牌存儲策略 .accessTokenConverter(jwtAccessTokenConverter); } //省略代碼... }
{ "exp": 1572682831, "user_name": "macro", "authorities": [ "admin" ], "jti": "c1a0645a-28b5-4468-b4c7-9623131853af", "client_id": "admin", "scope": [ "all" ] }
有時候咱們須要擴展JWT中存儲的內容,這裏咱們在JWT中擴展一個key爲enhance
,value爲enhance info
的數據。
/** * Jwt內容加強器 * Created by macro on 2019/10/8. */ public class JwtTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map<String, Object> info = new HashMap<>(); info.put("enhance", "enhance info"); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info); return accessToken; } }
/** * 使用Jwt存儲token的配置 * Created by macro on 2019/10/8. */ @Configuration public class JwtTokenStoreConfig { //省略代碼... @Bean public JwtTokenEnhancer jwtTokenEnhancer() { return new JwtTokenEnhancer(); } }
/** * 認證服務器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserService userService; @Autowired @Qualifier("jwtTokenStore") private TokenStore tokenStore; @Autowired private JwtAccessTokenConverter jwtAccessTokenConverter; @Autowired private JwtTokenEnhancer jwtTokenEnhancer; /** * 使用密碼模式須要配置 */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { TokenEnhancerChain enhancerChain = new TokenEnhancerChain(); List<TokenEnhancer> delegates = new ArrayList<>(); delegates.add(jwtTokenEnhancer); //配置JWT的內容加強器 delegates.add(jwtAccessTokenConverter); enhancerChain.setTokenEnhancers(delegates); endpoints.authenticationManager(authenticationManager) .userDetailsService(userService) .tokenStore(tokenStore) //配置令牌存儲策略 .accessTokenConverter(jwtAccessTokenConverter) .tokenEnhancer(enhancerChain); } //省略代碼... }
{ "user_name": "macro", "scope": [ "all" ], "exp": 1572683821, "authorities": [ "admin" ], "jti": "1ed1b0d8-f4ea-45a7-8375-211001a51a9e", "client_id": "admin", "enhance": "enhance info" }
若是咱們須要獲取JWT中的信息,可使用一個叫jjwt的工具包。
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency>
/** * Created by macro on 2019/9/30. */ @RestController @RequestMapping("/user") public class UserController { @GetMapping("/getCurrentUser") public Object getCurrentUser(Authentication authentication, HttpServletRequest request) { String header = request.getHeader("Authorization"); String token = StrUtil.subAfter(header, "bearer ", false); return Jwts.parser() .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8)) .parseClaimsJws(token) .getBody(); } }
Authorization
頭中,訪問以下地址獲取信息:http://localhost:9401/user/getCurrentUser在Spring Cloud Security 中使用oauth2時,若是令牌失效了,可使用刷新令牌經過refresh_token的受權模式再次獲取access_token。
/** * 認證服務器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("admin") .secret(passwordEncoder.encode("admin123456")) .accessTokenValiditySeconds(3600) .refreshTokenValiditySeconds(864000) .redirectUris("http://www.baidu.com") .autoApprove(true) //自動受權配置 .scopes("all") .authorizedGrantTypes("authorization_code","password","refresh_token"); //添加受權模式 } }
springcloud-learning └── oauth2-jwt-server -- 使用jwt的oauth2認證測試服務
https://github.com/macrozheng/springcloud-learninggithub
mall項目全套學習教程連載中,關注公衆號第一時間獲取。web