spring cloud oauth2 jwt 使用示例

超、凢脫俗 2023-07-03 12:29 58阅读 0赞

spring cloud oauth2 jwt 使用示例

*****************************

认证服务器:authorization-server

*******************

配置文件

  1. spring:
  2. application:
  3. name: authorization-server
  4. server:
  5. port: 8081

*******************

config 层

JwtTokenStoreConfig:jwtTokenStore配置

  1. @Configuration
  2. public class JwtTokenStoreConfig {
  3. @Bean
  4. public JwtAccessTokenConverter initJwtAccessTokenConverter(){
  5. JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
  6. jwtAccessTokenConverter.setSigningKey("sign123456");
  7. return jwtAccessTokenConverter;
  8. }
  9. @Bean
  10. public JwtTokenStore initJwtTokenStore(){
  11. return new JwtTokenStore(initJwtAccessTokenConverter());
  12. }
  13. }

OAuth2ServerConfig:认证服务器配置

  1. @Configuration
  2. @EnableAuthorizationServer
  3. public class OAuth2ServerConfiguration extends AuthorizationServerConfigurerAdapter {
  4. @Resource
  5. private AuthenticationManager authenticationManager;
  6. @Resource
  7. private BCryptPasswordEncoder passwordEncoder;
  8. @Resource
  9. private UserService userService;
  10. @Resource
  11. private JwtTokenStore jwtTokenStore;
  12. @Resource
  13. private JwtAccessTokenConverter jwtAccessTokenConverter;
  14. @Override
  15. public void configure(AuthorizationServerEndpointsConfigurer authorizationServerEndpointsConfigurer) throws Exception {
  16. authorizationServerEndpointsConfigurer
  17. .tokenStore(jwtTokenStore)
  18. .accessTokenConverter(jwtAccessTokenConverter)
  19. .authenticationManager(authenticationManager)
  20. .userDetailsService(userService);
  21. }
  22. @Override
  23. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
  24. clients.inMemory().withClient("user")
  25. .secret(passwordEncoder.encode("123456"))
  26. .authorizedGrantTypes("authorization_code","refresh_token")
  27. .redirectUris("http://localhost:8082/redirect")
  28. .accessTokenValiditySeconds(3000)
  29. .autoApprove(true)
  30. .scopes("user");
  31. }
  32. @Override
  33. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
  34. security.allowFormAuthenticationForClients()
  35. .tokenKeyAccess("isAuthenticated()") //获取token
  36. .checkTokenAccess("isAuthenticated()"); //验证token
  37. }
  38. }

*****************************

资源服务器:resource-server

*******************

配置文件

  1. spring:
  2. application:
  3. name: resource-server
  4. server:
  5. port: 8082
  6. security:
  7. oauth2:
  8. client:
  9. client-id: user
  10. client-secret: 123456
  11. user-authorization-uri: http://localhost:8081/oauth/authorize
  12. access-token-uri: http://localhost:8081/oauth/token
  13. resource:
  14. jwt:
  15. key-uri: http://localhost:8081/oauth/token_key
  16. key-value: sign123456

*******************

config 层

JwtTokenStoreConfig:jwtTokenStore配置

  1. @Configuration
  2. public class JwtTokenStoreConfig {
  3. @Bean
  4. public JwtAccessTokenConverter initJwtAccessTokenConverter(){
  5. JwtAccessTokenConverter jwtAccessTokenConverter=new JwtAccessTokenConverter();
  6. jwtAccessTokenConverter.setSigningKey("sign123456");
  7. return jwtAccessTokenConverter;
  8. }
  9. @Bean
  10. public JwtTokenStore initJwtTokenStore(){
  11. return new JwtTokenStore(initJwtAccessTokenConverter());
  12. }
  13. }

OAuth2ResourceServerConfig:资源服务器配置

  1. @Configuration
  2. @EnableResourceServer
  3. public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
  4. @Resource
  5. private JwtTokenStore jwtTokenStore;
  6. @Override
  7. public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
  8. resources.tokenStore(jwtTokenStore);
  9. }
  10. @Override
  11. public void configure(HttpSecurity http) throws Exception {
  12. http.authorizeRequests().antMatchers("/hello").hasAuthority("admin")
  13. .antMatchers("/redirect").permitAll();
  14. }
  15. }

*******************

controller 层

  1. @RestController
  2. public class HelloController {
  3. @Value("${security.oauth2.client.access-token-uri}")
  4. private String accessTokenUri;
  5. @RequestMapping("/hello")
  6. public String hello(){
  7. return "hello world";
  8. }
  9. @RequestMapping("/redirect") //获取授权码时的回调地址,使用获得的授权码获取access_token
  10. public Map get(@RequestParam(value = "code") String code){
  11. OkHttpClient httpClient=new OkHttpClient();
  12. RequestBody requestBody=new FormBody.Builder()
  13. .add("grant_type","authorization_code")
  14. .add("client","user")
  15. .add("redirect_uri","http://localhost:8082/redirect")
  16. .add("code",code)
  17. .build();
  18. Request request=new Request.Builder()
  19. .url(accessTokenUri)
  20. .post(requestBody)
  21. .addHeader("Authorization","Basic dXNlcjoxMjM0NTY=")
  22. .build();
  23. Map result=null;
  24. try {
  25. Response response=httpClient.newCall(request).execute();
  26. System.out.println(response);
  27. ObjectMapper objectMapper=new ObjectMapper();
  28. result=objectMapper.readValue(Objects.requireNonNull(response.body()).string(),Map.class);
  29. System.out.println("access_token:"+result.get("access_token"));
  30. System.out.println("token_type:"+result.get("token_type"));
  31. System.out.println("refresh_token:"+result.get("refresh_token"));
  32. System.out.println("expires_in:"+result.get("expires_in"));
  33. System.out.println("scope:"+result.get("scope"));
  34. }catch (Exception e){
  35. System.out.println(e.getMessage());
  36. }
  37. return result;
  38. }
  39. }

*****************************

使用测试

*******************

获取token

localhost:8081/oauth/authorize

查询参数:client_id=user&response_type=code&redirect_uri=http://localhost:8082/redirect

  1. ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzkzMTYyNQ_size_16_color_FFFFFF_t_70][]

解码token

  1. ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzkzMTYyNQ_size_16_color_FFFFFF_t_70 1][]

*******************

获取后端数据

localhost:8082/hello,header设置为

  1. keyAuthorization
  2. valuebearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1ODEwODIwMzcsInVzZXJfbmFtZSI6Imd0bHgiLCJhdXRob3JpdGllcyI6WyJhZG1pbiJdLCJqdGkiOiI5NWE0NDEwNS01MTkxLTQ5NzktYTg1My0zMzVjZGM0MGUwNjIiLCJjbGllbnRfaWQiOiJ1c2VyIiwic2NvcGUiOlsidXNlciJdfQ.p2WUqo_bQU5faiBSe1CwWbCDMEdBVYzxcxPVb3U96ps
  3. ![watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzkzMTYyNQ_size_16_color_FFFFFF_t_70 2][]

发表评论

表情:
评论列表 (有 0 条评论,58人围观)

还没有评论,来说两句吧...

相关阅读