一. 项目数据准备
1.1 添加依赖
<dependencies><!--spring security--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><!--web起步依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--redis依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--fastjson依赖--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.33</version></dependency><!--jwt依赖--><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--mybatis plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency><!--lombok--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!--单元测试--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--security测试--><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-test</artifactId><scope>test</scope></dependency>
</dependencies>
spring:datasource:url: jdbc:mysql://localhost:3306/db_drugstore?characterEncoding=utf-8&serverTimezone=UTCusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driver
1.2 添加Redis相关配置
package com.liming.config;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import com.alibaba.fastjson.parser.ParserConfig;import java.nio.charset.Charset;/*** 描述:Redis使用FastJson序列化* 创建人: 黎明* 创建时间: 2023/10/26* 版本: 1.0.0*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");private Class<T> clazz;static {ParserConfig.getGlobalInstance().setAutoTypeSupport(true);}public FastJsonRedisSerializer(Class<T> clazz) {super();this.clazz = clazz;}@Overridepublic byte[] serialize(T t) throws SerializationException {if (t == null) {return new byte[0];}return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@Overridepublic T deserialize(byte[] bytes) throws SerializationException {if (bytes == null || bytes.length <= 0) {return null;}String str = new String(bytes, DEFAULT_CHARSET);return JSON.parseObject(str, clazz);}protected JavaType getJavaType(Class<?> clazz) {return TypeFactory.defaultInstance().constructType(clazz);}
}
package com.liming.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** 描述:Redis配置* 创建人: 黎明* 创建时间: 2023/10/26* 版本: 1.0.0*/
@Configuration
public class RedisConfig {@Bean@SuppressWarnings(value = {"unchecked", "rawtypes"})public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);FastJsonRedisSerializer serializer = new FastJsonRedisSerializer(Object.class);// 使用StringRedisSerializer来序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(serializer);// Hash的key也采用StringRedisSerializer的序列化方式template.setHashKeySerializer(new StringRedisSerializer());template.setHashValueSerializer(serializer);template.afterPropertiesSet();return template;}
}
1.3 工具类
package com.liming.utils;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;/*** 描述:JWT工具类* 创建人: 黎明* 创建时间: 2023/10/26* 版本: 1.0.0*/
public class JwtUtil {//有效期为public static final Long JWT_TTL = 60 * 60 * 1000L;// 60 * 60 *1000 一个小时//设置秘钥明文public static final String JWT_KEY = "itlils";public static String getUUID() {String token = UUID.randomUUID().toString().replaceAll("-", "");return token;}/*** 生成jtw** @param subject token中要存放的数据(json格式)* @return*/public static String createJWT(String subject) {JwtBuilder builder = getJwtBuilder(subject, null, getUUID());// 设置过期时间return builder.compact();}/*** 生成jtw** @param subject token中要存放的数据(json格式)* @param ttlMillis token超时时间* @return*/public static String createJWT(String subject, Long ttlMillis) {JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());// 设置过期时间return builder.compact();}private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;SecretKey secretKey = generalKey();long nowMillis = System.currentTimeMillis();Date now = new Date(nowMillis);if (ttlMillis == null) {ttlMillis = JwtUtil.JWT_TTL;}long expMillis = nowMillis + ttlMillis;Date expDate = new Date(expMillis);return Jwts.builder().setId(uuid) //唯一的ID.setSubject(subject) // 主题 可以是JSON数据.setIssuer("ydlclass") // 签发者.setIssuedAt(now) // 签发时间.signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名, 第二个参数为秘钥.setExpiration(expDate);}/*** 创建token** @param id* @param subject* @param ttlMillis* @return*/public static String createJWT(String id, String subject, Long ttlMillis) {JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);// 设置过期时间return builder.compact();}/*** 生成加密后的秘钥 secretKey** @return*/public static SecretKey generalKey() {byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");return key;}/*** 解析** @param jwt* @return* @throws Exception*/public static Claims parseJWT(String jwt) throws Exception {SecretKey secretKey = generalKey();return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();}
}
package com.liming.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import java.util.*;
import java.util.concurrent.TimeUnit;/*** 描述:redis缓存工具类* 创建人: 黎明* 创建时间: 2023/10/26* 版本: 1.0.0*/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {@Autowiredpublic RedisTemplate redisTemplate;/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值*/public <T> void setCacheObject(final String key, final T value) {redisTemplate.opsForValue().set(key, value);}/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值* @param timeout 时间* @param timeUnit 时间颗粒度*/public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {redisTemplate.opsForValue().set(key, value, timeout, timeUnit);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout) {return expire(key, timeout, TimeUnit.SECONDS);}/*** 设置有效时间** @param key Redis键* @param timeout 超时时间* @param unit 时间单位* @return true=设置成功;false=设置失败*/public boolean expire(final String key, final long timeout, final TimeUnit unit) {return redisTemplate.expire(key, timeout, unit);}/*** 获得缓存的基本对象。** @param key 缓存键值* @return 缓存键值对应的数据*/public <T> T getCacheObject(final String key) {ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 删除单个对象** @param key*/public boolean deleteObject(final String key) {return redisTemplate.delete(key);}/*** 删除集合对象** @param collection 多个对象* @return*/public long deleteObject(final Collection collection) {return redisTemplate.delete(collection);}/*** 缓存List数据** @param key 缓存的键值* @param dataList 待缓存的List数据* @return 缓存的对象*/public <T> long setCacheList(final String key, final List<T> dataList) {Long count = redisTemplate.opsForList().rightPushAll(key, dataList);return count == null ? 0 : count;}/*** 获得缓存的list对象** @param key 缓存的键值* @return 缓存键值对应的数据*/public <T> List<T> getCacheList(final String key) {return redisTemplate.opsForList().range(key, 0, -1);}/*** 缓存Set** @param key 缓存键值* @param dataSet 缓存的数据* @return 缓存数据的对象*/public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while (it.hasNext()) {setOperation.add(it.next());}return setOperation;}/*** 获得缓存的set** @param key* @return*/public <T> Set<T> getCacheSet(final String key) {return redisTemplate.opsForSet().members(key);}/*** 缓存Map** @param key* @param dataMap*/public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {if (dataMap != null) {redisTemplate.opsForHash().putAll(key, dataMap);}}/*** 获得缓存的Map** @param key* @return*/public <T> Map<String, T> getCacheMap(final String key) {return redisTemplate.opsForHash().entries(key);}/*** 往Hash中存入数据** @param key Redis键* @param hKey Hash键* @param value 值*/public <T> void setCacheMapValue(final String key, final String hKey, final T value) {redisTemplate.opsForHash().put(key, hKey, value);}/*** 获取Hash中的数据** @param key Redis键* @param hKey Hash键* @return Hash中的对象*/public <T> T getCacheMapValue(final String key, final String hKey) {HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();return opsForHash.get(key, hKey);}/*** 删除Hash中的数据** @param key* @param hkey*/public void delCacheMapValue(final String key, final String hkey) {HashOperations hashOperations = redisTemplate.opsForHash();hashOperations.delete(key, hkey);}/*** 获取多个Hash中的数据** @param key Redis键* @param hKeys Hash键集合* @return Hash对象集合*/public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {return redisTemplate.opsForHash().multiGet(key, hKeys);}/*** 获得缓存的基本对象列表** @param pattern 字符串前缀* @return 对象列表*/public Collection<String> keys(final String pattern) {return redisTemplate.keys(pattern);}
}
/*** 描述:web工具类* 创建人: 黎明* 创建时间: 2023/10/26* 版本: 1.0.0*/
public class WebUtils {/*** 将字符串渲染到客户端** @param response 渲染对象* @param string 待渲染的字符串* @return null*/public static String renderString(HttpServletResponse response, String string) {try {response.setStatus(200);response.setContentType("application/json");response.setCharacterEncoding("utf-8");response.getWriter().print(string);} catch (IOException e) {e.printStackTrace();}return null;}
}
1.4 实体类
/*** 描述:用户* 创建人: 黎明* 创建时间: 2023/10/26* 版本: 1.0.0*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_user")
public class User implements Serializable {private static final long serialVersionUID = 1L;/*** 主键*/@TableId(type = IdType.AUTO)private Long id;/*** 用户名*/private String userName;/*** 昵称*/private String nickName;/*** 密码*/private String password;/*** 账号状态(0正常 1停用)*/private String status;/*** 邮箱*/private String email;/*** 手机号*/private String phonenumber;/*** 用户性别(0男,1女,2未知)*/private String sex;/*** 头像*/private String avatar;/*** 用户类型(0管理员,1普通用户)*/private String userType;/*** 创建人的用户id*/private Long createBy;/*** 创建时间*/private Date createTime;/*** 更新人*/private Long updateBy;/*** 更新时间*/private Date updateTime;/*** 删除标志(0代表未删除,1代表已删除)*/private Integer delFlag;
}
1.4 数据库表设计
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',`user_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '用户名',`nick_name` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '昵称',`password` varchar(64) NOT NULL DEFAULT 'NULL' COMMENT '密码',`status` char(1) DEFAULT '0' COMMENT '账号状态(0正常 1停用)',`email` varchar(64) DEFAULT NULL COMMENT '邮箱',`phonenumber` varchar(32) DEFAULT NULL COMMENT '手机号',`sex` char(1) DEFAULT NULL COMMENT '用户性别(0男,1女,2未知)',`avatar` varchar(128) DEFAULT NULL COMMENT '头像',`user_type` char(1) NOT NULL DEFAULT '1' COMMENT '用户类型(0管理员,1普通用户)',`create_by` bigint DEFAULT NULL COMMENT '创建人的用户id',`create_time` datetime DEFAULT NULL COMMENT '创建时间',`update_by` bigint DEFAULT NULL COMMENT '更新人',`update_time` datetime DEFAULT NULL COMMENT '更新时间',`del_flag` int DEFAULT '0' COMMENT '删除标志(0代表未删除,1代表已删除)',PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户表';-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('1', 'liming', '黎明', '$2a$10$CLZ2BaVAaNnWJAi49MfdG.Tl9m4hKhMJOTNpPI34ftMnjQOLGl.M6', '0', '123@qq.com', '13012345678', '0', 'a', '1', '1', '2023-10-26 18:52:41', '1', '2023-10-26 18:52:49', '0');
二.数据库校验用户
自定义一个
UserDetailsService
的实现类,让SpringSecurity使用我们的实现类
。从数据库中查询用户名和密码。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {@Autowiredprivate UserMapper userMapper;/*** 按用户名加载用户** @param username 用户名* @return {@link UserDetails}* @throws UsernameNotFoundException 用户名未发现异常*/@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 1.根据用户名获取数据库中用户信息LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();lqw.eq(User::getUserName, username);User user = userMapper.selectOne(lqw);if (Objects.isNull(user)) {throw new RuntimeException("用户名错误!");}// 2.@TODO 获取用户权限信息// 3.返回UserDetails对象return new LoginUser(user);}
}
因为UserDetailsService
方法的返回值是UserDetails
类型,所以需要定义一个类,实现该接口,把用户信息封装在其中。
@Data
@NoArgsConstructor
@AllArgsConstructor
public class LoginUser implements UserDetails {private User user;/*** 获取权限** @return {@link Collection}<{@link ?} {@link extends} {@link GrantedAuthority}>*/@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return null;}/*** 得到密码** @return {@link String}*/@Overridepublic String getPassword() {return user.getPassword();}/*** 获得用户名** @return {@link String}*/@Overridepublic String getUsername() {return user.getUserName();}/*** 账户未过期吗?** @return boolean*/@Overridepublic boolean isAccountNonExpired() {return true;}/*** 账户未锁定吗?** @return boolean*/@Overridepublic boolean isAccountNonLocked() {return true;}/*** 证书是否未过期?** @return boolean*/@Overridepublic boolean isCredentialsNonExpired() {return true;}/*** 启用了** @return boolean*/@Overridepublic boolean isEnabled() {return true;}
}
三.密码加密存储
实际项目中我们不会把密码明文存储在数据库中, 我们一般使用SpringSecurity为我们提供的
BCryptPasswordEncoder
,我们只需要使用把BCryptPasswordEncoder对象注入Spring容器中,SpringSecurity就会使用该PasswordEncoder来进行密码校验。 我们可以定义一个SpringSecurity的配置类。
@Configuration
public class SecurityConfig{@Beanpublic PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
}
使用BCryptPasswordEncoder
的好处:
- BCryptPasswordEncoder可以实现自动帮我们密码加盐,这样虽然我们的密码是一样的,但是加盐后在数据库中存储的密文密码是不一样的
- BCryptPasswordEncoder加密网址:https://portal.he3app.com/home/extension/bcrypt-hash?posthog_from=Searchbar
四.自定义登陆接口
4.1 自定义一个controller登陆接口
@RestController
public class LoginController {@Autowiredprivate LoginService loginService;@PostMapping("/user/login")public Result<Map<String, String>> login(@RequestBody User user) {return loginService.login(user);}}
4.2 放行自定义登陆接口
@Configuration
public class SecurityConfig {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http//关闭csrf.csrf().disable()//不通过Session获取SecurityContext.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()// 对于登录接口 允许匿名访问.antMatchers("/user/login").anonymous()// 除上面外的所有请求全部需要鉴权认证.anyRequest().authenticated();return http.build();}// 注入AuthenticationConfiguration@Autowiredprivate AuthenticationConfiguration authenticationConfiguration;/*** 通过authenticationConfiguration获取一个AuthenticationManager实例* 这个Bean可以在其他地方被引用,以实现用户认证的功能** @return {@link AuthenticationManager}* @throws Exception 异常*/@Beanpublic AuthenticationManager authenticationManager() throws Exception {AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();return authenticationManager;}}
4.3 使用AuthenticationManager auth方法进行验证
@Service
public class LoginServiceImpl implements LoginService {@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate RedisCache redisCache;/*** 登录** @param user 用户* @return {@link Result}*/@Overridepublic Result<Map<String, String>> login(User user) {// 3.使用AuthenticationManager authenticate方法进行验证UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);//校验失败了if (Objects.isNull(authenticate)) {throw new AppException(AppExceptionCodeMsg.USERNAME_PASSWORD_ERR);}// 4.自己生成jwt给前端LoginUser loginUser = (LoginUser) (authenticate.getPrincipal());String userId = loginUser.getUser().getId().toString();String jwt = JwtUtil.createJWT(userId);Map<String, String> map = new HashMap<>();map.put("token", jwt);// 5.系统用户相关所有信息放入redisredisCache.setCacheObject("login:" + userId, loginUser);return Result.success("登陆成功", map);}
}
五.认证过滤器
spring securirt自带16个过滤器链,我们前面自定义修改了
UsernamePasswordAuthenticationFilter
过滤器,但是后面的过滤器也需要使用Authentication
用户登录权限信息,所有我们就需要一个认证过滤器将用户的信息Authentication存入到SecurityContextHolder
供其他过滤器使用
实现步骤:
-
获取token
-
解析token
-
获取userid
-
封装Authentication
-
存入SecurityContextHolder
/*** 描述:JWT身份验证令牌过滤器* 创建人: 黎明* 创建时间: 2023/10/27* 版本: 1.0.0* OncePerRequestFilter 只走一次,请求前*/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {@Autowiredprivate RedisCache redisCache;@Overrideprotected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {// 1.获取token header的tokenString token = request.getHeader("token");if (!StringUtils.hasText(token)) {//放行,让后面的过滤器执行报错filterChain.doFilter(request, response);return;}// 2.解析tokenString userId;try {Claims claims = JwtUtil.parseJWT(token);userId = claims.getSubject();} catch (Exception e) {throw new AppException(AppExceptionCodeMsg.TOKEN_ERR);}// 3.获取userId, redis获取用户信息LoginUser loginUser = redisCache.getCacheObject("login:" + userId);if (Objects.isNull(loginUser)) {throw new AppException(AppExceptionCodeMsg.LOGIN_ERR);}// 4.封装AuthenticationUsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken= new UsernamePasswordAuthenticationToken(loginUser, null, null);// 5.存入SecurityContextHolderSecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);//放行,让后面的过滤器执行filterChain.doFilter(request, response);}
}
过滤器配置(SecurityConfig文件中):
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;//把token校验过滤器添加到过滤器链中(filterChain方法中)
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
测试登录:
未登陆访问资源的话
携带token访问
六.退出登陆
写一个退出接口,删除reids里的key
即可
LoginController:
@PostMapping("/user/logout")
public Result logout(){return loginService.logout();
}
LoginServiceImpl:
@Overridepublic Result logout() {Authentication authentication = SecurityContextHolder.getContext().getAuthentication();LoginUser loginUser = (LoginUser) authentication.getPrincipal();Long userId = loginUser.getUser().getId();redisCache.deleteObject("login:" + userId);return Result.success("退出成功!");}
测试:
登陆:
访问资源:
退出:
再访问资源: