Spring Security 在 Spring Boot 中集成 JWT + RSA【分布式】

1.1 简介

1.1.1 分布式认证

  分布式认证即用户只需要登录一次就可以访问所有互相信任的子系统。在每台服务中都有一个 session 但是各个 session 之间时无法共享资源的,所以 session 不能作为单点登录的解决方案。单点登录一般分为两个部分:
 ♞ 用户认证:这一环节主要是用户向认证服务发起认证请求,认证服务给用户返回一个成功的令牌 token,主要在认证服务中完成,注意认证服务只能有一个。
 ♞ 身份校验:这一环节是用户携带 token 去访问其他服务时,在其他服务中要对 token 的真伪进行检验,主要在资源服务中完成,资源服务可以有很多个。

在这里插入图片描述

  从分布式认证流程中,我们不难发现,这中间起最关键作用的就是 token,token 的安全与否,直接关系到系统的健壮性,本篇我们选择使用 JWT 来实现 token 的生成和校验。

1.1.2 JWT

  JWT(JSON Web Token)是一个十分优秀的分布式认证解决方案,JWT 是一套开放的标准(RFC 7519),它定义了一种紧凑且自 URL 安全的方式,以 JSON 对象的方式在各方之间安全地进行信息传输。由于此信息是经过数字签名的,因此是可以被验证和信任的。可以使用密钥(secret)使用HMAC算法或者使用 RSA 或 ECDSA 的公有/私有密钥对 JWT 进行签名。JWT 生成的 token 由三部分组成:
 ♞ 头部:主要设置一些规范信息,签名部分的编码格式就在头部中声明
 ♞ 载荷:token 中存放有效信息的部分,比如用户名,用户角色,过期时间等,但是不要放密码,会泄露
 ♞ 签名:将头部与载荷分别采用 base64 编码后,用.相连,再加入盐,最后使用头部声明的编码类型进行编码,就得到了签名
  虽然可以对 JWT 进行加密用来在各方之间提供保密性,但我们还是重点关注下签名的令牌(token)本身,签名的令牌可以验证其中包含的声明的完整性,而加密的令牌则将这些声明在其他方的面前进行隐藏,以提供安全性。当使用公钥/私钥对对令牌进行签名时,签名还可以证明只有持有私钥的一方才是对其进行签名的一方。


1.1.3 RSA(非对称加密)

  RSA 是 1977 年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。当时他们三人都在麻省理工学院工作。RSA 就是他们三人姓氏开头字母拼在一起组成的。RSA 公开密钥密码体制是一种使用不同的加密密钥与解密密钥,由已知加密密钥推导出解密密钥在计算上是不可行的密码体制 。
  在公开密钥密码体制中,加密密钥(即公钥 PK)是公开信息,而解密密钥(即私钥 SK)是需要保密的。虽然私钥是由公钥决定的,但却不能根据公钥计算出私钥 。正是基于这种理论,1978 年出现了著名的 RSA 算法,它通常是先生成一对 RSA 密钥,其中之一是私钥,由用户保存;另一个为公钥,可对外公开,甚至可在网络服务器中注册。





1.2 相关工具类

1.2.1 JSON 工具类

<!--jackson包-->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9</version>
</dependency>
<!--日志包-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-logging</artifactId>
    <version>2.2.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.9.9</version>
</dependency>
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description Json 工具类
 */
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;
        }
    }
}

1.2.2 载荷类

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 载荷类,token 中存放有效信息
 */
 @Data
public class Payload<T> {
    private String id;
    private T userInfo;
    private Date expiration;
}

1.2.3 JWT 工具类

<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>
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description JWT 工具类
 */
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)
                .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)
                .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;
    }
}


1.2.4 RSA 工具类

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description RSA 工具类
 */
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);
    }
}
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/20
 * @description 测试 RsaUtils
 */
public class RsaTest {
	// 指定公钥和私钥的路径
    private String publicKeyFile = "C:\\Users\\softw\\Desktop\\key\\pub_key";
    private String privateKeyFile = "C:\\Users\\softw\\Desktop\\key\\pri_key";

    /**
     * 测试生成密钥
     * @author Demo_Null
     * @date 2020/10/20
     * @param  
     * @return void
     **/
    @Test
    public void generateKey() throws Exception {
        RsaUtils.generateKey(publicKeyFile, privateKeyFile, "Demo_Null", 2048);
    }

    /**
     * 测试获取公钥
     * @author Demo_Null
     * @date 2020/10/20
     * @param
     * @return void
     **/
    @Test
    public void getPublicKey() throws Exception {
        System.out.println(RsaUtils.getPublicKey(publicKeyFile));
    }

    /**
     * 测试获取私钥
     * @author Demo_Null
     * @date 2020/10/20
     * @param
     * @return void
     **/
    @Test
    public void getPrivateKey() throws Exception {
        System.out.println(RsaUtils.getPrivateKey(privateKeyFile));
    }

}





1.3 分布式认证思路

1.3.1 集中式认证分析

  Spring Security 主要是通过过滤器链来实现认证和身份校验的,我们重点来看一下用户认证和身份校验的过滤器。在分布式中我们需要重写的也就是以下几个过滤器。

☞ UsernamePasswordAuthenticationFilter
  AbstractAuthenticationProcessingFilter.doFilter() 调用 UsernamePasswordAuthenticationFilter 中的 attemptAuthentication 实现认证功能,该方法将表单请求(POST)的信息赋值给 UsernamePasswordAuthenticationToken (authRequest),然后调用 getAuthenticationManager().authenticate(authRequest) 对用户密码的正确性进行验证,认证失败就抛出异常,成功就返回 Authentication 对象。

在这里插入图片描述

☞ AbstractAuthenticationProcessingFilter
  第二个过滤器就是 UsernamePasswordAuthenticationFilter 的父类 AbstractAuthenticationProcessingFilter, 该过滤器中提供 successfulAuthentication 方法进行验证用户是否登录,认证通过之后将认证信息存放到 session。

在这里插入图片描述

☞ BasicAuthenticationFilter
  BasicAuthenticationFilter 过滤器中 doFilterInternal 方法会去验证 session 中是否由用户信息来判断用户是否登录,验证成功则放行,验证失败则抛出异常。

在这里插入图片描述


1.3.2 分布式认证分析

☞ 用户认证
  由于,分布式项目,多数是前后端分离的架构设计,我们要满足可以接受异步 POST 的认证请求参数,需要修改 UsernamePasswordAuthenticationFilter 过滤器中 attemptAuthentication 方法,让其能够接收请求体。另外,默认 successfulAuthentication 方法在认证通过后,是把用户信息直接放入 session 就完事了,现在我们需要修改这个方法,在认证通过后生成 token 并返回给用户。

☞ 身份校验
  原本的 BasicAuthenticationFilter 过滤器中 doFilterlnternal 方法校验用户是否登录,就是看 session 中是否有用户信息,我们要修改为,验证用户携带的 token 是否合法,并解析出用户信息,交给 SpringSecurity,以便于后续的授权功能可以正常使用。





1.4 认证服务

1.4.1 用户类与角色类

  像这种其他服务也会使用到的实体类我们一般会将其放到一个单独的模块中,这里为了省事直接放到了 utils 模块中。对于这两个类不熟悉的可以看 Spring Security 在 Spring Boot 中的使用【集中式】

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 角色类
 */
public class SysRole implements GrantedAuthority {

    private Integer id;
    private String roleName;
    private String roleDesc;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @JsonIgnore
    @Override
    public String getAuthority() {
        return roleName;
    }
}
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 用户类
 */
public class SysUser implements UserDetails {

    private Integer id;
    private String username;
    private String password;
    private Integer status;
    private List<SysRole> roles;

    public List<SysRole> getRoles() {
        return roles;
    }

    public void setRoles(List<SysRole> roles) {
        this.roles = roles;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    @JsonIgnore
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isEnabled() {
        return true;
    }
}

1.4.2 配置文件

# 省略数据库操作配置
server:
  port: 8081
  
rsa: 
  key:
    public: "C:\Users\softw\Desktop\key\pub_key"
    private: "C:\\Users\\softw\\Desktop\\key\\pri_key"
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 解析公钥私钥配置类
 */
@Component  // 也可以启动类 @EnableConfigurationProperties(RsaKeyProperties.class) 注解进行配置
@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;
    }
}

1.4.3 重写过滤器

☞ UsernamePasswordAuthenticationFilter

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 重写 attemptAuthentication 和 successfulAuthentication 方法
 */
public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter {
	// 不属于 Ioc 管理,无法注入,只能通过构造方法
    private AuthenticationManager authenticationManager;
    private RsaKeyProperties prop;

    /**
     * 构造方法,谁使用谁提供 AuthenticationManager,RsaKeyProperties
     * @author Demo_Null
     * @date 2020/10/20
     * @param authenticationManager
     * @param prop  
     * @return 
     **/
    public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
        this.authenticationManager = authenticationManager;
        this.prop = prop;
    }

    /**
     * 提供用户认证
     * @author Demo_Null
     * @date 2020/10/20
     * @param request
     * @param response  
     * @return org.springframework.security.core.Authentication
     **/
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 
    																		throws AuthenticationException {
        try {
        	// 获取用户登录信息,由于这里前端参数是 application/json 所以不能使用 getParameter 获取
            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);
        }
    }

    /**
     * 认证成功后返回 token
     * @author Demo_Null
     * @date 2020/10/20
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @return void
     **/
    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());
        // 生成 token, 最后一个参数为过期时间单位是分钟
        String token = JwtUtils.generateTokenExpireInMinutes(user, prop.getPrivateKey(), 24 * 60);
        // 返回 token
        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();
        }
    }

}

☞ BasicAuthenticationFilter

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 重写 doFilterInternal
 */
public class JwtVerifyFilter extends BasicAuthenticationFilter {

    private RsaKeyProperties prop;

    public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
        super(authenticationManager);
        this.prop = prop;
    }

    /**
     * 验证用户携带的 token 是否正确
     * @author gaohu9712@163.com
     * @date 2020/10/20
     * @param request
     * @param response
     * @param chain  
     * @return void
     **/
    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 {
            try {
                // 如果携带了正确格式的 token 要先得到 token
                String token = header.replace("Bearer ", "");
                // 验证 token 是否正确
                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());
                    // 认证信息放到 session
                    SecurityContextHolder.getContext().setAuthentication(authResult);
                    // 放行
                    chain.doFilter(request, response);
                }
            } catch (Exception e) {
                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();
            }
        }
    }
}

1.4.4 Spring Security 配置类

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RsaKeyProperties prop;

    @Autowired
    private UserServiceImpl UserServiceImpl;

    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //指定认证对象的来源
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(UserServiceImpl).passwordEncoder(passwordEncoder());
    }
    //SpringSecurity配置信息
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()		// 关闭 csrf
            .disable()
            // 授权后才能访问
            .authorizeRequests()	
            .anyRequest().authenticated()
            .and()
            // 自定义过滤器
            .addFilter(new JwtLoginFilter(super.authenticationManager(), prop))
            .addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
            // 禁用 session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);		
    }
}

1.4.5 示例

需要注意的是,请求参数不要使用 form 表单,要使用 json,返回的 token 在头里面。
在这里插入图片描述
在这里插入图片描述





1.5 资源服务

1.5.1 配置文件

# 省略数据库等配置
server:
  port: 8082

rsa:
  key:
    # 此处一定不要有私钥
    pubKeyFile: 'C:\Users\softw\Desktop\key\pub_key'
/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 解析公钥配置类, 私钥只能认证服务含有
 */
@Component
@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;
    }
}

1.5.2 校验认证

这里直接拷贝认证服务中的 JwtVerifyFilter,在资源服务中只需要验证 token 是否正确。

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/19
 * @description 重写 doFilterInternal
 */
public class JwtVerifyFilter extends BasicAuthenticationFilter {

    private RsaKeyProperties prop;

    public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) {
        super(authenticationManager);
        this.prop = prop;
    }

    /**
     * 验证用户携带的 token 是否正确
     * @author gaohu9712@163.com
     * @date 2020/10/20
     * @param request
     * @param response
     * @param chain  
     * @return void
     **/
    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 {
            try {
                // 如果携带了正确格式的 token 要先得到 token
                String token = header.replace("Bearer ", "");
                // 验证 token 是否正确
                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());
                    // 认证信息放到 session
                    SecurityContextHolder.getContext().setAuthentication(authResult);
                    // 放行
                    chain.doFilter(request, response);
                }
            } catch (Exception e) {
                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();
            }
        }
    }
}

1.5.3 Spring Security 配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RsaKeyProperties prop;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //SpringSecurity配置信息
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JwtVerifyFilter(super.authenticationManager(), prop))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

1.5.4 示例

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/10/20
 * @description 测试接口
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @GetMapping("/find")
    @Secured("ROLE_USER")
    public String find() {
        return "查询成功!";
    }
}

在这里插入图片描述
在这里插入图片描述





1.6 项目文件

1.6.1 项目目录

在这里插入图片描述

1.6.2 项目地址

☞ GitHub



Spring Boot 是一个用于构建微服务的开源框架,它能够快速搭建项目并且提供了许多便捷的功能和特性。Spring Security 是一个用于处理认证和授权的框架,可以保护我们的应用程序免受恶意攻击。JWT(JSON Web Token)是一种用于身份验证的开放标准,可以被用于安全地传输信息。Spring MVC 是一个用于构建 Web 应用程序的框架,它能够处理 HTTP 请求和响应。MyBatis 是一个用于操作数据库的框架,可以简化数据库操作和提高效率。Redis 是一种高性能的键值存储系统,可以用于缓存与数据存储。 基于这些技术,可以搭建一个商城项目。Spring Boot 可以用于构建商城项目的后端服务,Spring Security 可以确保用户信息的安全性,JWT 可以用于用户的身份验证,Spring MVC 可以处理前端请求,MyBatis 可以操作数据库,Redis 可以用于缓存用户信息和商品信息。 商城项目的后端可以使用 Spring BootSpring Security 来搭建,通过 JWT 来处理用户的身份验证和授权。数据库操作可以使用 MyBatis 来简化与提高效率,同时可以利用 Redis 来缓存一些常用的数据和信息,提升系统的性能。前端请求则可以通过 Spring MVC 来处理,实现商城项目的整体功能。 综上所述,借助于 Spring BootSpring SecurityJWTSpring MVC、MyBatis 和 Redis 这些技术,可以构建出一个高性能、安全可靠的商城项目,为用户提供良好的购物体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值