zoukankan      html  css  js  c++  java
  • SpringSecurity整合JWT

    分布式认证概念说明
    分布式认证,即我们常说的单点登录,简称SSO,指的是在多应用系统的项目中,用户只需要登录一次,就可以访
    问所有互相信任的应用系统。
    分布式认证流程图
    首先,我们要明确,在分布式项目中,每台服务器都有各自独立的session,而这些session之间是无法直接共享资
    源的,所以,session通常不能被作为单点登录的技术方案。
    最合理的单点登录方案流程如下图所示:

    总结一下,单点登录的实现分两大环节:
    用户认证:这一环节主要是用户向认证服务器发起认证请求,认证服务器给用户返回一个成功的令牌token
    主要在认证服务器中完成,即图中的A系统,注意A系统只能有一个。
    身份校验:这一环节是用户携带token去访问其他服务器时,在其他服务器中要对token的真伪进行检验,主
    要在资源服务器中完成,即图中的B系统,这里B系统可以有很多个。
    JWT介绍
    从分布式认证流程中,我们不难发现,这中间起最关键作用的就是tokentoken的安全与否,直接关系到系统的
    健壮性,这里我们选择使用JWT来实现token的生成和校验。
    JWT,全称JSON Web Token,官网地址https://jwt.io,是一款出色的分布式身份校验方案。可以生成token,也可
    以解析检验token

    JWT生成的token由三部分组成:
    头部:主要设置一些规范信息,签名部分的编码格式就在头部中声明。
    载荷:token中存放有效信息的部分,比如用户名,用户角色,过期时间等,但是不要放密码,会泄露!
    签名:将头部与载荷分别采用base64编码后,用“.”相连,再加入盐,最后使用头部声明的编码类型进行编码,就得到了签名。

    JWT生成token的安全性分析:
    JWT生成的token组成上来看,要想避免token被伪造,主要就得看签名部分了,而签名部分又有三部分组成,其
    中头部和载荷的base64编码,几乎是透明的,毫无安全性可言,那么最终守护token安全的重担就落在了加入的盐
    上面了!

    非对称加密RSA介绍
    基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端
    私钥加密,持有私钥或公钥才可以解密
    公钥加密,持有私钥才可解密
    优点:安全,难以破解
    缺点:算法比较耗时,为了安全,可以接受
    历史:三位数学家RivestShamir Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三
    个人的名字缩写:RSA
    JWT相关工具类
    jar

    <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt-api</artifactId>
                <version>0.10.7</version>
            </dependency>
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt-impl</artifactId>
                <version>0.10.7</version>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>io.jsonwebtoken</groupId>
                <artifactId>jjwt-jackson</artifactId>
                <version>0.10.7</version>
                <scope>runtime</scope>
            </dependency>

    载荷对象 

    @Data
    public class Payload<T> {
        private String id;
        private T userInfo;
        private Date expiration;
    }
    public class JsonUtils {
    
        public static final ObjectMapper mapper = new ObjectMapper();
    
        private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    
        public static String toString(Object obj) {
            if (obj == null) {
                return null;
            }
            if (obj.getClass() == String.class) {
                return (String) obj;
            }
            try {
                return mapper.writeValueAsString(obj);
            } catch (JsonProcessingException e) {
                logger.error("json序列化出错:" + obj, e);
                return null;
            }
        }
    
        public static <T> T toBean(String json, Class<T> tClass) {
            try {
                return mapper.readValue(json, tClass);
            } catch (IOException e) {
                logger.error("json解析出错:" + json, e);
                return null;
            }
        }
    
        public static <E> List<E> toList(String json, Class<E> eClass) {
            try {
                return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
            } catch (IOException e) {
                logger.error("json解析出错:" + json, e);
                return null;
            }
        }
    
        public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
            try {
                return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
            } catch (IOException e) {
                logger.error("json解析出错:" + json, e);
                return null;
            }
        }
    
        public static <T> T nativeRead(String json, TypeReference<T> type) {
            try {
                return mapper.readValue(json, type);
            } catch (IOException e) {
                logger.error("json解析出错:" + json, e);
                return null;
            }
        }
    }
    public class JwtUtils {
    
        private static final String JWT_PAYLOAD_USER_KEY = "user";
    
        /**
         * 私钥加密token
         *
         * @param userInfo   载荷中的数据
         * @param privateKey 私钥
         * @param expire     过期时间,单位分钟
         * @return JWT
         */
        public static String generateTokenExpireInMinutes(Object userInfo, PrivateKey privateKey, int expire) {
            return Jwts.builder()
                    .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
                    .setId(createJTI())
                    .setExpiration(DateTime.now().plusMinutes(expire).toDate())
                    .signWith(privateKey, SignatureAlgorithm.RS256)
                    .compact();
        }
    
        /**
         * 私钥加密token
         *
         * @param userInfo   载荷中的数据
         * @param privateKey 私钥
         * @param expire     过期时间,单位秒
         * @return JWT
         */
        public static String generateTokenExpireInSeconds(Object userInfo, PrivateKey privateKey, int expire) {
            return Jwts.builder()
                    .claim(JWT_PAYLOAD_USER_KEY, JsonUtils.toString(userInfo))
                    .setId(createJTI())
                    .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                    .signWith(privateKey, SignatureAlgorithm.RS256)
                    .compact();
        }
    
        /**
         * 公钥解析token
         *
         * @param token     用户请求中的token
         * @param publicKey 公钥
         * @return Jws<Claims>
         */
        private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
            return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
        }
    
        private static String createJTI() {
            return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
        }
    
        /**
         * 获取token中的用户信息
         *
         * @param token     用户请求中的令牌
         * @param publicKey 公钥
         * @return 用户信息
         */
        public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> userType) {
            Jws<Claims> claimsJws = parserToken(token, publicKey);
            Claims body = claimsJws.getBody();
            Payload<T> claims = new Payload<>();
            claims.setId(body.getId());
            claims.setUserInfo(JsonUtils.toBean(body.get(JWT_PAYLOAD_USER_KEY).toString(), userType));
            claims.setExpiration(body.getExpiration());
            return claims;
        }
    
        /**
         * 获取token中的载荷信息
         *
         * @param token     用户请求中的令牌
         * @param publicKey 公钥
         * @return 用户信息
         */
        public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey) {
            Jws<Claims> claimsJws = parserToken(token, publicKey);
            Claims body = claimsJws.getBody();
            Payload<T> claims = new Payload<>();
            claims.setId(body.getId());
            claims.setExpiration(body.getExpiration());
            return claims;
        }
    }
    public class RsaUtils {
    
        private static final int DEFAULT_KEY_SIZE = 2048;
        /**
         * 从文件中读取公钥
         *
         * @param filename 公钥保存路径,相对于classpath
         * @return 公钥对象
         * @throws Exception
         */
        public static PublicKey getPublicKey(String filename) throws Exception {
            byte[] bytes = readFile(filename);
            return getPublicKey(bytes);
        }
    
        /**
         * 从文件中读取密钥
         *
         * @param filename 私钥保存路径,相对于classpath
         * @return 私钥对象
         * @throws Exception
         */
        public static PrivateKey getPrivateKey(String filename) throws Exception {
            byte[] bytes = readFile(filename);
            return getPrivateKey(bytes);
        }
    
        /**
         * 获取公钥
         *
         * @param bytes 公钥的字节形式
         * @return
         * @throws Exception
         */
        private static PublicKey getPublicKey(byte[] bytes) throws Exception {
            bytes = Base64.getDecoder().decode(bytes);
            X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePublic(spec);
        }
    
        /**
         * 获取密钥
         *
         * @param bytes 私钥的字节形式
         * @return
         * @throws Exception
         */
        private static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
            bytes = Base64.getDecoder().decode(bytes);
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            return factory.generatePrivate(spec);
        }
    
        /**
         * 根据密文,生存rsa公钥和私钥,并写入指定文件
         *
         * @param publicKeyFilename  公钥文件路径
         * @param privateKeyFilename 私钥文件路径
         * @param secret             生成密钥的密文
         */
        public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret, int keySize) throws Exception {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            SecureRandom secureRandom = new SecureRandom(secret.getBytes());
            keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
            KeyPair keyPair = keyPairGenerator.genKeyPair();
            // 获取公钥并写出
            byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
            publicKeyBytes = Base64.getEncoder().encode(publicKeyBytes);
            writeFile(publicKeyFilename, publicKeyBytes);
            // 获取私钥并写出
            byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
            privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
            writeFile(privateKeyFilename, privateKeyBytes);
        }
    
        private static byte[] readFile(String fileName) throws Exception {
            return Files.readAllBytes(new File(fileName).toPath());
        }
    
        private static void writeFile(String destPath, byte[] bytes) throws IOException {
            File dest = new File(destPath);
            if (!dest.exists()) {
                dest.createNewFile();
            }
            Files.write(dest.toPath(), bytes);
        }
    }

    回顾集中式认证流程
    用户认证:
    使用UsernamePasswordAuthenticationFilter过滤器中attemptAuthentication方法实现认证功能,该过滤
    器父类中successfulAuthentication方法实现认证成功后的操作。
    身份校验:
    使用BasicAuthenticationFilter过滤器中doFilterInternal方法验证是否登录,以决定能否进入后续过滤器。
    分析分布式认证流程
    用户认证:
    由于,分布式项目,多数是前后端分离的架构设计,我们要满足可以接受异步post的认证请求参数,需要修
    UsernamePasswordAuthenticationFilter过滤器中attemptAuthentication方法,让其能够接收请求体。

    另外,默认successfulAuthentication方法在认证通过后,是把用户信息直接放入session就完事了,现在我
    们需要修改这个方法,在认证通过后生成token并返回给用户。
    身份校验:
    原来BasicAuthenticationFilter过滤器中doFilterInternal方法校验用户是否登录,就是看session中是否有用
    户信息,我们要修改为,验证用户携带的token是否合法,并解析出用户信息,交给SpringSecurity,以便于
    后续的授权功能可以正常使用。

    SpringSecurity+JWT+RSA分布式认证实现 

    public class RsaUtilsTest {
    
        private String privateFilePath = "D:\id_key_rsa";
        private String publicFilePath = "D:\id_key_rsa.pub";
    
        @Test
        public void generateKey() throws Exception {
            RsaUtils.generateKey(publicFilePath, privateFilePath, "topcheer", 2048);
        }
    
        @Test
        public void getPublicKey() throws Exception {
            System.out.println(RsaUtils.getPublicKey(publicFilePath));
        }
    
        @Test
        public void getPrivateKey() throws Exception {
            System.out.println(RsaUtils.getPrivateKey(privateFilePath));
        }
    
    
        @Test
        public void testGetPublicKey() {
        }
    
        @Test
        public void testGetPrivateKey() {
        }
    
        @Test
        public void testGenerateKey() {
        }
    }

     认证服务
    创建认证服务工程并导入jar

      <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>com.topcheer</groupId>
                <artifactId>topcheer_common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>
        </dependencies>

    配置文件

    server:
      port: 9001
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql:///security_authority
        username: root
        password: 123456
    mybatis:
      type-aliases-package: com.topcheer.domain
      configuration:
        map-underscore-to-camel-case: true
    logging:
      level:
        com.topcheer: debug
    rsa:
      key:
        pubKeyFile: D:id_key_rsa.pub
        priKeyFile: D:id_key_rsa

    提供解析公钥和私钥的配置类

    @ConfigurationProperties("rsa.key")
    public class RsaKeyProperties {
    
        private String pubKeyFile;
        private String priKeyFile;
    
        private PublicKey publicKey;
        private PrivateKey privateKey;
    
        @PostConstruct
        public void createRsaKey() throws Exception {
            publicKey = RsaUtils.getPublicKey(pubKeyFile);
            privateKey = RsaUtils.getPrivateKey(priKeyFile);
        }
    
        public String getPubKeyFile() {
            return pubKeyFile;
        }
    
        public void setPubKeyFile(String pubKeyFile) {
            this.pubKeyFile = pubKeyFile;
        }
    
        public String getPriKeyFile() {
            return priKeyFile;
        }
    
        public void setPriKeyFile(String priKeyFile) {
            this.priKeyFile = priKeyFile;
        }
    
        public PublicKey getPublicKey() {
            return publicKey;
        }
    
        public void setPublicKey(PublicKey publicKey) {
            this.publicKey = publicKey;
        }
    
        public PrivateKey getPrivateKey() {
            return privateKey;
        }
    
        public void setPrivateKey(PrivateKey privateKey) {
            this.privateKey = privateKey;
        }
    }

    配置类

    @SpringBootApplication
    @MapperScan("com.topcheer.mapper")
    @EnableConfigurationProperties(RsaKeyProperties.class)
    public class AuthServerApplication {
        public static void main(String[] args) {
            SpringApplication.run(AuthServerApplication.class, args);
        }
    }

    认证过滤器:

    public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
    
        private AuthenticationManager authenticationManager;
        private RsaKeyProperties prop;
    
        public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
            this.authenticationManager = authenticationManager;
            this.prop = prop;
        }
    
        @Override
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
            try {
                SysUser sysUser = new ObjectMapper().readValue(request.getInputStream(), SysUser.class);
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(sysUser.getUsername(), sysUser.getPassword());
                return authenticationManager.authenticate(authRequest);
            }catch (Exception e){
                try {
                    response.setContentType("application/json;charset=utf-8");
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    PrintWriter out = response.getWriter();
                    Map resultMap = new HashMap();
                    resultMap.put("code", HttpServletResponse.SC_UNAUTHORIZED);
                    resultMap.put("msg", "用户名或密码错误!");
                    out.write(new ObjectMapper().writeValueAsString(resultMap));
                    out.flush();
                    out.close();
                }catch (Exception outEx){
                    outEx.printStackTrace();
                }
                throw new RuntimeException(e);
            }
        }
    
        @Override
        public void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
            SysUser user = new SysUser();
            user.setUsername(authResult.getName());
            user.setRoles((List<SysRole>) authResult.getAuthorities());
            String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
            response.addHeader("Authorization", "Bearer "+token);
            try {
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_OK);
                PrintWriter out = response.getWriter();
                Map resultMap = new HashMap();
                resultMap.put("code", HttpServletResponse.SC_OK);
                resultMap.put("msg", "认证通过!");
                out.write(new ObjectMapper().writeValueAsString(resultMap));
                out.flush();
                out.close();
            }catch (Exception outEx){
                outEx.printStackTrace();
            }
        }
    
    }
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled=true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserService userService;
    
        @Autowired
        private RsaKeyProperties prop;
    
        @Bean
        public BCryptPasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        //指定认证对象的来源
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
        }
        //SpringSecurity配置信息
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/product").hasAnyRole("USER")
                .anyRequest()
                .authenticated()
                .and()
                .addFilter(new JwtLoginFilter(super.authenticationManager(), prop))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    启动测试认证服务
    认证请求 

     

    资源服务
    资源服务可以有很多个,这里只拿产品服务为例,记住,资源服务中只能通过公钥验证认证。不能签发token
    创建产品服务并导入jar
    根据实际业务导包即可,咱们就暂时和认证服务一样了。

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>
            <dependency>
                <groupId>com.topcheer</groupId>
                <artifactId>topcheer_common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>
        </dependencies>

    编写产品服务配置文件
    切记这里只能有公钥地址!

    server:
      port: 9002
    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql:///security_authority
        username: root
        password: 123456
    mybatis:
      type-aliases-package: com.topcheer.domain
      configuration:
        map-underscore-to-camel-case: true
    logging:
      level:
        com.topcheer: debug
    rsa:
      key:
        pubKeyFile: D:id_key_rsa.pub

    编写读取公钥的配置类

    @ConfigurationProperties("rsa.key")
    public class RsaKeyProperties {
    
        private String pubKeyFile;
    
        private PublicKey publicKey;
    
        @PostConstruct
        public void createRsaKey() throws Exception {
            publicKey = RsaUtils.getPublicKey(pubKeyFile);
        }
    
        public String getPubKeyFile() {
            return pubKeyFile;
        }
    
        public void setPubKeyFile(String pubKeyFile) {
            this.pubKeyFile = pubKeyFile;
        }
    
        public PublicKey getPublicKey() {
            return publicKey;
        }
    
        public void setPublicKey(PublicKey publicKey) {
            this.publicKey = publicKey;
        }
    
    }
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled=true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private RsaKeyProperties prop;
    
        //SpringSecurity配置信息
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/product").hasAnyRole("USER")
                .anyRequest()
                .authenticated()
                .and()
                .addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }
    }

    web层

    @RestController
    @RequestMapping("/product")
    public class ProductController {
    
        @Secured("ROLE_PRODUCT")
        @RequestMapping("/findAll")
        public String findAll(){
            return "产品列表查询成功!";
        }
    
    }

     验证token服务器

    public class JwtVerifyFilter extends BasicAuthenticationFilter {
    
        private RsaKeyProperties prop;
    
        public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
            super(authenticationManager);
            this.prop = prop;
        }
    
        @Override
        public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
            String header = request.getHeader("Authorization");
            if (header == null || !header.startsWith("Bearer ")) {
                //如果携带错误的token,则给用户提示请登录!
                chain.doFilter(request, response);
                response.setContentType("application/json;charset=utf-8");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                PrintWriter out = response.getWriter();
                Map resultMap = new HashMap();
                resultMap.put("code", HttpServletResponse.SC_FORBIDDEN);
                resultMap.put("msg", "请登录!");
                out.write(new ObjectMapper().writeValueAsString(resultMap));
                out.flush();
                out.close();
            } else {
                //如果携带了正确格式的token要先得到token
                String token = header.replace("Bearer ", "");
                //验证tken是否正确
                Payload<SysUser> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), SysUser.class);
                SysUser user = payload.getUserInfo();
                if(user!=null){
                    UsernamePasswordAuthenticationToken authResult = new UsernamePasswordAuthenticationToken(user.getUsername(), null, user.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(authResult);
                    chain.doFilter(request, response);
                }
            }
        }
    
    
    
    
    }

    测试:

    携带上面的token进行访问这个服务器

    当这个用户没有权限的时候,就报这个错,下面给用户添加权限

     

     

     

  • 相关阅读:
    HTML5就是现在:深入了解Polyfills
    dot.js-js模板引擎使用,教程,入门
    js操作dom对象
    JavaScript中this详解
    浅谈JavaScript中的string拥有方法的原因
    函数定义方式
    Jquery的跨域调用
    数据结构与算法之美-排序(下)
    CLR via C#学习笔记-第十三章-定义接口、继承接口
    CLR via C#学习笔记-第十二章-可验证性和约束
  • 原文地址:https://www.cnblogs.com/dalianpai/p/12416487.html
Copyright © 2011-2022 走看看