Spring Cloud Security 整合 JWT

一、基础概述

  • 在Oauth2 + Spring Cloud Security的项目环境中, Spring Cloud Security 默认把访问令牌保存在内存中。而在分布式环境中,我们可以利用JWT或Redis存储令牌信息,以便于多个服务的使用。

  • JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。

  • JWT token 的格式为 header.payload.signature

    • header

      {
        "alg": "HS256",
        "typ": "JWT"
      }
      
    • payload

      {
        "exp": 1572682831,
        "user_name": "zhangsan",
        "authorities": [
          "client"
        ],
        "jti": "c1a0645a-28b5-4468-b4c7-9623131853af",
        "client_id": "admin",
        "scope": [
          "all"
        ]
      }
      
    • signature

      signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败

  • JWT token 的官网:https://jwt.io/

    在这里插入图片描述

二、利用Redis存储令牌

  • 添加依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • 添加配置

    server:
      port: 8080
      servlet:
        context-path: /
    
    spring:
      application:
        name: oauth-redis
      redis:
        database: 0
        host: 127.0.0.1
        port: 6379
        password: 
    
  • 添加Redis存储配置类

    @Configuration
    public class RedisTokenStoreConfig {
    
        @Autowired
        private RedisConnectionFactory redisConnectionFactory;
    
        @Bean
        public TokenStore redisTokenStore (){
            return new RedisTokenStore(redisConnectionFactory);
        }
    }
    
  • 修改认证服务器配置类

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Autowired
        private UserDetailServiceImpl userDetailsService;
    
        @Autowired
        @Qualifier("redisTokenStore")
        private TokenStore tokenStore;
        
        /**
         * 使用密码模式所需配置
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService)
                	// 配置令牌存储策略
                	.tokenStore(tokenStore);
        }
    }
    
  • 获取访问令牌

    使用Postman工具

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

  • 查看Redis信息

    在这里插入图片描述

三、利用JWT存储令牌

  • 添加JWT存储配置类

    @Configuration
    public class JwtTokenStoreConfig {
    
        @Bean
        public TokenStore jwtTokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }
    
        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
            // 配置JWT使用的秘钥
            accessTokenConverter.setSigningKey("test_key");
            return accessTokenConverter;
        }
    }
    
  • 修改认证服务器配置类

    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Autowired
        private UserDetailServiceImpl userDetailsService;
    
        @Autowired
        @Qualifier("jwtTokenStore")
        private TokenStore tokenStore;
        @Autowired
        private JwtAccessTokenConverter jwtAccessTokenConverter;
        
        /**
         * 使用密码模式所需配置
         */
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints.authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService)
                	// 配置令牌存储策略
                	.tokenStore(tokenStore)
                    .accessTokenConverter(jwtAccessTokenConverter);
        }
    }
    
  • 获取访问令牌

    使用Postman工具

    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述

  • 查看JWT信息

    将得到的 access_token 去https://jwt.io/ 网站进行解析

    在这里插入图片描述

四、扩展JWT的存储内容

  • 添加内容扩展类

    public class JwtTokenEnhancer implements TokenEnhancer {
        
        @Override
        public OAuth2AccessToken enhance(
            	OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
            
            Map<String, Object> info = new HashMap<>();
            info.put("add_key", "add_value");
            ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
            
            return accessToken;
        }
    }
    
  • 修改JWT存储配置类

    @Configuration
    public class JwtTokenStoreConfig {
    
        @Bean
        public TokenStore jwtTokenStore() {
            return new JwtTokenStore(jwtAccessTokenConverter());
        }
    
        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter();
            // 配置JWT使用的秘钥
            accessTokenConverter.setSigningKey("test_key");
            return accessTokenConverter;
        }
        
        @Bean
        public JwtTokenEnhancer jwtTokenEnhancer() {
            return new JwtTokenEnhancer();
        }
    }
    
  • 修改认证服务器配置类

    ![20210325194754](C:/Users/jihongye/Documents/Scrshot/20210325194754.png@Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Autowired
        private UserDetailServiceImpl userDetailsService;
    
        @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); 
            delegates.add(jwtAccessTokenConverter);
            
            enhancerChain.setTokenEnhancers(delegates);
            
            endpoints.authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService)
                	// 配置令牌存储策略
                	.tokenStore(tokenStore)
                    .accessTokenConverter(jwtAccessTokenConverter)
                	.tokenEnhancer(enhancerChain);
        }
    }
    
  • 查看JWT信息

    在这里插入图片描述

五、解析JWT存储的内容

  • 添加依赖

    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.0</version>
    </dependency>
    
  • 测试使用

    public class ApplicationTest {
        
        public void test() {
             public void test() {
            String token = "jwt的token字符串";
            
            Object obj = Jwts.parser()
                    .setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                    .parseClaimsJws(token)
                    .getBody();
            
         	System.out.println(object);   
        }   
        }
    }
    

【源码地址】:GitHub

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Spring Cloud是一个基于Spring Boot的开发工具,用于快速构建分布式系统的微服务框架。它提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡、断路器、网关等,使得开发者可以更加方便地构建和管理微服务。 Spring SecuritySpring框架中的一个安全框架,用于提供身份认证和授权功能。它可以与Spring Cloud集成,为微服务提供安全保障。 JWT(JSON Web Token)是一种轻量级的身份认证和授权机制,它使用JSON格式来传递信息。在Spring Cloud中,可以使用JWT来实现微服务之间的安全通信,保证数据的安全性和完整性。 ### 回答2: Spring Cloud是一个开源的分布式系统开发框架,它基于Spring Boot,能够帮助开发者快速构建云原生应用程序。Spring Cloud提供了一系列的组件,例如服务注册与发现(Eureka)、服务网关(Zuul)、配置中心(Config)等,可以协助开发者实现微服务架构。 Spring SecuritySpring框架提供的一种安全框架,它能够为应用程序提供认证和授权的功能。Spring Security基于过滤器链的机制,可以对请求进行安全验证。开发者可以通过配置来定义访问控制规则,保护应用程序的资源。 JWT(JSON Web Token)是一种用于身份验证和访问控制的标准方法,它通过在身份验证完成后生成一个令牌,并将该令牌发送给客户端,客户端在后续的请求中通过该令牌进行身份验证。JWT由三部分组成,分别是头部、载荷和签名。头部和载荷使用Base64进行编码,然后使用一个密钥进行签名,确保JWT的安全性。 在使用Spring CloudSpring Security构建分布式系统时,可以使用JWT作为认证和授权的方式。具体做法是,当用户进行身份验证成功后,生成一个JWT令牌,并将该令牌返回给客户端。客户端在后续的请求中,将令牌作为Authorization头部的内容发送给服务端。服务端接收到请求后,解析JWT令牌,验证其合法性,并根据令牌中的信息来判断用户的身份和权限。通过这种方式,可以实现无状态的分布式身份验证和访问控制。 总结来说,Spring Cloud可以帮助开发者构建分布式系统,Spring Security可以提供身份验证和授权的功能,而JWT可以作为一种安全的认证和授权方式在分布式系统中使用。这三者相互结合,可以帮助开发者构建安全、可靠的分布式应用程序。 ### 回答3: Spring Cloud是一个基于Spring Boot的开发工具集,它提供了一系列的分布式系统开发工具,其中包括了分布式配置中心、服务注册与发现、消息总线、负载均衡、熔断器、数据流处理等。Spring Cloud的目标是帮助开发者快速构建适应于云环境的分布式系统。 Spring SecuritySpring官方提供的安全框架,它可以用于保护Spring应用程序免受各种攻击,例如身份验证、授权、防止跨站点请求伪造等。Spring Security使用一种基于过滤器链的方式来处理HTTP请求,通过配置一系列的过滤器,可以实现对请求的鉴权和授权处理。 JWT(JSON Web Token)是一种用于跨域身份验证的开放标准。它可以在用户和服务器之间传输信息,并且能够对信息进行校验和解析。JWT一般由三部分组成:头部、载荷和签名。头部包含了令牌的类型和加密算法,载荷包含了需要传输的信息,签名用于验证令牌的合法性。 在使用Spring Cloud时,可以结合Spring SecurityJWT来进行身份验证和授权。我们可以通过配置Spring Security的过滤器链来验证JWT的有效性,并在每个请求中进行用户身份的鉴权。通过使用JWT,我们可以避免传统的基于Session的身份验证方式,实现无状态的分布式身份验证。 总结起来,Spring Cloud是一个分布式系统开发工具集,Spring Security是一个安全框架,JWT是一种用于跨域身份验证的开放标准。在使用Spring Cloud进行分布式系统开发时,可以结合Spring SecurityJWT来实现身份验证和授权的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程小吉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值