您当前的位置: 首页 >  spring

SpringSecurity整合SpringBoot——集中式版与分布式版

发布时间:2021-10-06 10:29:54 ,浏览量:8

目录
  • 1.集中式版
    • 1.1.整合认证第一版
      • 1.1.1.搭建SpringBoot环境
      • 1.1.2.加入Spring Security
    • 1.2.整合认证第二版【加入jsp使用自定义认证页面】
      • 1.2.1.加入自定义的jsp页面
      • 1.2.2.提供SpringSecurity配置类
      • 1.2.3.修改相应的控制器方法并配置视图解析器
      • 1.2.4.使用tomcat插件启动项目
    • 1.3.整合认证第三版【数据库认证】
      • 1.3.1.加入通用mapper
        • (1)导入数据库操作相关jar包
        • (2)在application.yml配置文件中添加数据库操作相关配置
        • (3)在启动类上添加扫描dao接口包注解
      • 1.3.2.使用数据库实现认证
        • (1)创建角色和用户的pojo对象(直接使用SpringSecurity的角色规范)
        • (2)提供角色和用户的mapper接口
        • (3)提供认证service接口以及实现类
        • (4)修改配置类WebSecurityConfig
      • 1.3.3.使用数据库中的用户信息进行测试
    • 1.4.整合实现授权功能
      • 1.4.1.在配置类上添加开启方法级的授权注解
      • 1.4.2.在产品控制器类上添加注解
      • 1.4.3.进行测试
  • 2.分布式版
    • 2.1.分布式认证
      • 2.1.1.分布式认证概念说明
      • 2.1.2.分布式认证流程图
      • 2.1.3.JWT介绍
    • 2.2.创建父工程与common工具模块
    • 2.3.相关准备工作
    • 2.4.认证模块搭建
    • 2.5.资源服务器搭建

本文章的笔记整理来自黑马视频https://www.bilibili.com/video/BV1vt4y1i7zA?p=33,相关资料可以在该视频的评论区进行获取

注:如果对Spring Security不是很了解的读者,可以先去阅读Spring Security——入门介绍这篇文章。

1.集中式版 1.1.整合认证第一版 1.1.1.搭建SpringBoot环境

(1)在IDEA中创建一个名为spring_security_family空项目 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 (2)创建一个新的Module 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 (3)导入SpringBoot相关的jar包

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0 public static void main(String[] args) { SpringApplication.run(SpringSecurityApplication.class); } } 
# application.yml
server:
  port: 8080

(5)测试

package com.itheima.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/product") public class ProductController { @RequestMapping @ResponseBody public String findAll(){ return "success"; } } 

先在SpringBoot启动类中启动SpringBoot,然后在浏览器地址栏中输入http://localhost:8080/product,如果得到下面的结果,则说明测试成功。 在这里插入图片描述

1.1.2.加入Spring Security

(1)在pom.xml中加入Spring Security依赖

<dependency> <groupId>org.springframework.boot //SpringSecurity配置信息 //指定认证对象的来源 public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user") .password("{noop}123") .roles("USER"); } public void configure(HttpSecurity http) throws Exception{ http.authorizeRequests() .antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll() .antMatchers("/**").hasAnyRole("USER","ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp") .loginProcessingUrl("/login") .successForwardUrl("/index.jsp") .failureForwardUrl("/failer.jsp") .permitAll() .and() .logout() .logoutSuccessUrl("/logout") .invalidateHttpSession(true) .permitAll() .logoutSuccessUrl("/login.jsp") .and() .csrf() .disable(); //为了方便测试,此处先关闭csrf } } 
1.2.3.修改相应的控制器方法并配置视图解析器

(1)修改相应的控制器方法

package com.itheima.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/product") public class ProductController { @RequestMapping("/findAll") public String findAll(){ //跳转页面的前后缀已经在application.yml中配置 return "product-list"; } } 

(2)在application.yml中配置视图解析器

spring:
  mvc:
    view:
      prefix: /pages/
      suffix: .jsp
1.2.4.使用tomcat插件启动项目

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

1.3.整合认证第三版【数据库认证】 1.3.1.加入通用mapper (1)导入数据库操作相关jar包
<dependency> <groupId>mysql 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; } } 
package com.itheima.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.Collection; import java.util.List; 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:不参与json字符串的转换 @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; } } 
(2)提供角色和用户的mapper接口
package com.itheima.mapper; import com.itheima.domain.SysRole; import org.apache.ibatis.annotations.Select; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface RoleMapper extends Mapper<SysRole> { //根据用户id查询角色 @Select("SELECT r.id, r.role_name roleName, r.role_desc roleDesc " + "FROM sys_role r, sys_user_role ur " + "WHERE r.id=ur.rid AND ur.uid=#{uid}") List<SysRole> findByUid(Integer uid); } 
package com.itheima.mapper; import com.itheima.domain.SysUser; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface UserMapper extends Mapper<SysUser>{ //根据用户名查询用户(包括用户所拥有的角色) @Select("select * from sys_user where username = #{username}") @Results({ @Result(id = true, property = "id", column = "id"), @Result(property = "roles", column = "id", javaType = List.class, many = @Many(select = "com.itheima.mapper.RoleMapper.findByUid")) }) SysUser findByName(String username); } 
(3)提供认证service接口以及实现类
package com.itheima.service; import org.springframework.security.core.userdetails.UserDetailsService; public interface UserService extends UserDetailsService { } 
package com.itheima.service.impl; import com.itheima.mapper.UserMapper; import com.itheima.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException{ return userMapper.findByName(s); } } 
(4)修改配置类WebSecurityConfig
package com.itheima.config; import com.itheima.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserService userService; //将加密对象注册到Spring容器中 @Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } //SpringSecurity配置信息 //指定认证对象的来源 public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } public void configure(HttpSecurity http) throws Exception{ http.authorizeRequests() .antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll() .antMatchers("/**").hasAnyRole("USER","ADMIN") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login.jsp") .loginProcessingUrl("/login") .successForwardUrl("/index.jsp") .failureForwardUrl("/failer.jsp") .permitAll() .and() .logout() .logoutSuccessUrl("/logout") .invalidateHttpSession(true) .permitAll() .logoutSuccessUrl("/login.jsp") .and() .csrf() .disable(); //为了方便测试,此处先关闭csrf } } 
1.3.3.使用数据库中的用户信息进行测试

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

1.4.整合实现授权功能 1.4.1.在配置类上添加开启方法级的授权注解

在这里插入图片描述

1.4.2.在产品控制器类上添加注解

在这里插入图片描述

1.4.3.进行测试

(1)此处使用不具有ROLE_PRODUCT角色的用户xiaoma进行测试 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 (2)自定义异常页面 编写异常处理器拦截403异常

package com.itheima.advice; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class HandlerControllerException { @ExceptionHandler(RuntimeException.class) public String handException(RuntimeException e){ if(e instanceof AccessDeniedException){ return "redirect:/403.jsp"; } return "redirect:/500.jsp"; } } 

再次测试时便出现以下自定义的异常页面: 在这里插入图片描述

2.分布式版 2.1.分布式认证 2.1.1.分布式认证概念说明

分布式认证,即我们常说的单点登录,简称 SSO,指的是在多应用系统的项目中,用户只需要登录一次,就可以访问所有互相信任的应用系统。

2.1.2.分布式认证流程图

首先,需要明确一点的是,在分布式项目中,每台服务器都有各自独立的session,而这些session之间是无法直接共享资源的,所以session通常不能被作为单点登录的技术方案。最合理的单点登录方案流程如下图所示:

在这里插入图片描述 总结一下,单点登录的实现分两大环节: ① 用户认证:这一环节主要是用户向认证服务器发起认证请求,认证服务器给用户返回一个成功的令牌token,主要在认证服务器中完成,即图中的A系统,注意A系统只能有一个。 ② 身份校验:这一环节是用户携带token去访问其他服务器时,在其他服务器中要对token的真伪进行检验,主要在资源服务器中完成,即图中的B系统,这里B系统可以有很多个。

2.1.3.JWT介绍

(1)概念说明 从分布式认证流程中,我们不难发现,这中间起最关键作用的就是token,token的安全与否,直接关系到系统的健壮性,这里我们选择使用JWT来实现 token 的生成和校验。JWT,全称 JSON Web Token,官网地址为https://jwt.io,是一款出色的分布式身份校验方案。可以生成 token,也可以解析检验 token。JWT 生成的 token 由三部分组成:

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

(2)JWT生成 token 的安全性分析 ① 从JWT生成的 token 组成上来看,要想避免token被伪造,主要就得看签名部分了,而签名部分又有三部分组成,其中头部和载荷的base64编码,几乎是透明的,毫无安全性可言,那么最终守护token安全的重担就落在了加入的盐上面了! ② 试想:如果生成token所用的盐与解析token时加入的盐是一样的。岂不是类似于中国人民银行把人民币防伪技术公开了?大家可以用这个盐来解析token,就能用来伪造token。 ③ 这时,我们就需要对盐采用非对称加密的方式进行加密,以达到生成token与校验token方所用的盐不一致的安全效果!

(3)非对称加密 RSA 介绍 ① 基本原理:同时生成两把密钥:私钥和公钥,私钥隐秘保存,公钥可以下发给信任客户端

私钥加密 持有私钥或公钥才可以解密 公钥加密 持有私钥才可解密

② 优点:安全,难以破解 ③ 缺点:算法比较耗时,为了安全,可以接受 ④ 历史:三位数学家Rivest、Shamir 和 Adleman 设计了一种算法,可以实现非对称加密。这种算法用他们三个人的名字缩写:RSA。

2.2.创建父工程与common工具模块

(1)创建父工程(不存放业务代码) 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述 (2)创建common工具模块 在这里插入图片描述 在这里插入图片描述

2.3.相关准备工作

以下准备工作都是针对common工具模块而言 (1)在pom.xml中导入JWT以及其它相关的jar包

<dependencies> <dependency> <groupId>io.jsonwebtoken <dependency> <groupId>com.fasterxml.jackson.core <dependency> <groupId>org.springframework.boot private String id; private T userInfo; private Date expiration; } 
package com.itheima.utils; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; 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; } } } 
package com.itheima.utils; import com.itheima.domain.Payload; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jws; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.joda.time.DateTime; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Base64; import java.util.UUID; /**
 * 生成token以及校验token相关方法
 */ 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*/ 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; } } 
package com.itheima.utils; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.security.*; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; 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); } } 

在测试方法中生成公钥和私钥

package com.itheima.utils; import org.junit.Test; public class RsaUtilsTest { private String privateFilePath = "E:\\auth_key\\id_key_rsa"; private String publicFilePath = "E:\\auth_key\\id_key_rsa.pub"; @Test public void generateKey() throws Exception { RsaUtils.generateKey(publicFilePath, privateFilePath, "itheima", 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)); } } 
2.4.认证模块搭建

(1)创建一个名为heima-auth_server的认证模块 在这里插入图片描述 在这里插入图片描述 (2)导入相关依赖

<dependencies> <dependency> <groupId>org.springframework.boot 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; } } 

(5)创建SpringBoot启动类AuthServerApplication

package com.itheima.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; //SpringBoot启动类 @SpringBootApplication @MapperScan("com.itheima.mapper") @EnableConfigurationProperties(RsaKeyProperties.class) public class AuthServerApplication { public static void main(String[] args) { SpringApplication.run(AuthServerApplication.class,args); } } 

(6)将集中式版本中domain、controller、service、mapper包中的代码复制过来,并作适当修改。 (7)重写认证的过滤器

package com.itheima.filter; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.config.RsaKeyProperties; import com.itheima.domain.SysRole; import com.itheima.domain.SysUser; import com.itheima.utils.JwtUtils; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; public class JwtLoginFilter extends UsernamePasswordAuthenticationFilter { private AuthenticationManager authenticationManager; private RsaKeyProperties prop; public JwtLoginFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) { this.authenticationManager = authenticationManager; this.prop = prop; } 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); } } 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(); } } } 

(8)验证认证的过滤器

package com.itheima.filter; import com.fasterxml.jackson.databind.ObjectMapper; import com.itheima.config.RsaKeyProperties; import com.itheima.domain.Payload; import com.itheima.domain.SysUser; import com.itheima.utils.JwtUtils; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; public class JwtVerifyFilter extends BasicAuthenticationFilter { private RsaKeyProperties prop; public JwtVerifyFilter(AuthenticationManager authenticationManager, RsaKeyProperties prop) { super(authenticationManager); this.prop = prop; } 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); } } } } 

(9)配置类编写

package com.itheima.config; import com.itheima.filter.JwtLoginFilter; import com.itheima.filter.JwtVerifyFilter; import com.itheima.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @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(); } //指定认证对象的来源 public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userService).passwordEncoder(passwordEncoder()); } //SpringSecurity配置信息 public void configure(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests() .antMatchers("/product").hasAnyRole("USER") .anyRequest() .authenticated() .and() .addFilter(new JwtLoginFilter(super.authenticationManager(), prop)) .addFilter(new JwtVerifyFilter(super.authenticationManager(), prop)) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } } 

(10)测试 ① 模拟登录,并获取登录成功后生成的token 在这里插入图片描述 在这里插入图片描述 ② 查询产品列表 在这里插入图片描述

2.5.资源服务器搭建

(1)创建资源服务器模块 在这里插入图片描述 在这里插入图片描述 (2)在pom.xml中导入相关的依赖

<dependencies> <dependency> <groupId>org.springframework.boot public static void main(String[] args) { SpringApplication.run(AuthSourceApplication.class, args); } } 

(5)复制认证服务中的用户对象,角色对象和校验认证的接口

(6)复制认证服务中SpringSecurity配置类做修改(去掉“增加自定义认证过滤器”即可!)

package com.itheima.config; import com.itheima.filter.JwtVerifyFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled=true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private RsaKeyProperties prop; //SpringSecurity配置信息 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); } } 

(7)编写产品控制器方法

package com.itheima.controller; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/product") public class ProductController { @Secured("ROLE_PRODUCT") @RequestMapping("/findAll") public String findAll(){ return "产品列表查询成功!"; } } 

此时目录结构如下图: 在这里插入图片描述 (8)测试(之前登录生成的token还未失效) 在这里插入图片描述 这里可以看出,当端口号为9002,并且在进行产品管理请求时,携带之前登录生成的token,便可以无需登录而请求成功,这样就简单地实现了分布式的认证。

关注
打赏
1688896170
查看更多评论

暂无认证

  • 8浏览

    0关注

    105695博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.3273s