前言
网关作为整个微服务入口,在网关做认证授权既可以提前过滤不合法或过期的请求,又能让其他服务专做自身业务,不再关心令牌和权限问题。在集成过程中,选用的微服务版本为Greenwich.SR2,springboot版本以及security版本都为2.1.6.RELEASE,security每个版本的的实现有蛮大差异的。比如在2.0.1.RELEASE版在装载权限tag的时候是不需要带ROLE_
前缀的,而2.1.6.RELEASE看源码得知需要自己拼接前缀。由于公司加密问题,项目不能放置外网,后续篇幅可能偏长,尽量每一步都贴清除,方便初学者少踩坑。但原理就读者自己去体会。
构建项目
eureka : 注册中心
common : 公用模块,放置其他服务公用的部分,可以不用
api-gateway : zuul集成security实现登录认证
auth-center : zuul集成security实现认证授权
父 pom.xml
4.0.0
com.babaznkj.com
zuul-auth
pom
1.0-SNAPSHOT
eureka
api-gateway
common
auth-center
8
8
UTF-8
UTF-8
1.8
Greenwich.SR2
1.3.2
1.1.9
2.0.2
1.0.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
com.babaznkj.com
common
${project.version}
org.springframework.boot
spring-boot-maven-plugin
- common 模块
JwtProperties.java
,这个版本验证 Authorization的时候截取了前6位,且已Bearer
开头,故在生成jwt的时候要拼接前缀,这个文件就用来读取默认配置的。package com.baba.security.common.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @Author wulongbo * @Date 2021/11/4 9:49 * @Version 1.0 */ @Data @Component @ConfigurationProperties("baba.security.jwt") public class JwtProperties { private String secret; private String url; private String header; private String prefix; private Integer expiration; private String language; }
JwtTokenAuthenticationFilter.java
,由于过滤器中无法注入bean,故采用从spring上下文中获取。做全局异常处理,要抛出自定义异常可以先抛如controller中,当然这里采用了另外一种方式。这里实现了动态验签以及唯一登录。package com.baba.security.common.config; import com.baba.security.common.constant.RedisConstant; import com.baba.security.common.enums.ResultCode; import com.baba.security.common.exception.DefinitException; import com.baba.security.common.utils.JwtUtils; import com.baba.security.common.utils.RedisUtils; import com.baba.security.common.utils.SpringUtils; import io.jsonwebtoken.JwtException; import org.springframework.context.ApplicationContext; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.servlet.HandlerExceptionResolver; import javax.servlet.FilterChain; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Authenticate requests with header 'Authorization: Bearer jwt-token'. * * @author wulongbo 2021/10/18 */ public class JwtTokenAuthenticationFilter extends OncePerRequestFilter { // private final JwtAuthenticationConfig config; private final JwtProperties config; public JwtTokenAuthenticationFilter(JwtProperties config) { this.config = config; } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse rsp, FilterChain filterChain) throws ServletException, IOException { HandlerExceptionResolver resolver = null; try { RedisUtils redisUtil = SpringUtils.getBean(RedisUtils.class); // filter过滤器使用Autowired注入Bean为null ServletContext context = req.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context); resolver = ctx.getBean("handlerExceptionResolver", HandlerExceptionResolver.class); String userAgent = req.getHeader("user-agent").toLowerCase(); String salt = null; //获取token String token = req.getHeader(config.getHeader()); if (token != null && token.startsWith(config.getPrefix() + " ")) { token = token.replace(config.getPrefix() + " ", ""); String id = redisUtil.get(token); if (StringUtils.isEmpty(id)) { resolver.resolveException(req, rsp, null, new DefinitException(ResultCode.REDIS_CACHE_BLANK)); return; } if (userAgent.indexOf("micromessenger") != -1) { //微信 } else if (userAgent.indexOf("android") != -1 || userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1 || userAgent.indexOf("ipod") != -1) { //安卓 或者 苹果 salt = redisUtil.get(RedisConstant.PREFIX_APP + id); } else { //电脑 salt = redisUtil.get(RedisConstant.PREFIX_WEB + id); } if (StringUtils.isEmpty(salt)) { resolver.resolveException(req, rsp, null, new DefinitException(ResultCode.REDIS_SALT_BLANK)); return; } String username = JwtUtils.getUsername(token,salt); if (username != null) { List
roles = JwtUtils.getUserRole(token,salt); SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username, null, roles)); } } // resolver.resolveException(req, rsp, null, new JwtException(ResultCode.TOKEN_EXCEPTION.getMessage())); filterChain.doFilter(req, rsp); } catch (JwtException e) { resolver.resolveException(req, rsp, null, new JwtException(ResultCode.SAFETY_INVALID.getMessage())); } } } RedisConstant.java
,常量类。package com.baba.security.common.constant; /** * @author wulongbo 2021/10/18 */ public interface RedisConstant { String TOKEN_TEMPLATE = "token_%s"; String PREFIX_APP = "bbznkj_app_"; String PREFIX_WEB = "bbznkj_web_"; }
ResultCode.java
,枚举类可以规范响应,如是多国语言的系统可以考虑适用redis来解决。package com.baba.security.common.enums; /** * @Author wulongbo * @Date 2021/10/27 14:13 * @Version 1.0 */ /** * 异常处理状态码 */ public enum ResultCode { SUCCESS(0, "请求成功"), FAILED(1001, "响应失败"), Unknown_Exception(-1, "未知异常"), SAFETY_INVALID(208,"该账号已在其他设备登录,签名已失效,请重新登录"), REDIS_CACHE_BLANK(6379, "缓存已失效,请重新登录"), REQUEST_URL_WRONG(401, "请求地址不存在"), REQUEST_BLANK(403, "请求接口无权限访问"), REDIS_SALT_BLANK(6333,"签名值缓存失效"), USER_NOT_FOUND(10001, "没有找到此用户"), USERNAME_NOT_BLANK(10002, "用户名不能为空"), USERNAME_EXIST(10003, "用户名已经存在"), USERTYPE_ERROR(100031, "用户类型不正确"), PHONE_WROND(10004, "手机号不正确"), SMS_CODE_ERROR(10007, "手机验证码不正确"), PHONE_EXIST(10008, "手机号已经存在"), USER_EMPTY_EXCEPTION(10009, "用户名、手机号或者邮箱为空"), USER_TOKEN_EXCEPTION(10010, "从TOKEN中未查到相关用户信息"), USERNAME_PASSWORD_EXCEPTION(10011, "用户名或者密码错误"), EMAIL_SERVER_ECCEPTION(10012, "阿里云邮件服务端出错"), EMAIL_CLIENT_ECCEPTION(10013, "阿里云邮件客户端出错"), EMAIL_SEND_ECCEPTION(10014, "阿里云邮件发送出错"), EMAIL_WROND(10015, "邮箱不正确"), EMAIL_CODE_WROND(10016, "邮箱验证码不正确"), EMAIL_EXIST(10017, "邮箱已经存在"), LOGIN_METHOD_WROND(209, "登录密码不正确"), CODE_EMPTY(10019, "验证码不为空"), PASSWORD_EMPTY(10020, "密码不为空"), TOKEN_EXCEPTION(10021, "TOKEN认证出错"), USER_AUTH_FAILD(10022, "用户认证失败"), USER_AUTH_SUCCESS(200, "用户认证授权成功"), USER_ACCESS_DENIED(10023, "用户无权限登录"), CODE_SEND_FAILD(10030, "验证码发送失败"), ACTION_MONGODB_ERROR(10100, "操作MONGODB数据库出错"), OPERATION_TOO_FREQUENT(10101, "请求过于频繁,请稍候再试"), CODE_EXIST(10023,"编号已存在"), TESTCODE_ERROR(10036,"提交数已达上限"), NAME_EXIST(10024,"名称已存在"), NOT_EXIST_EMAIL(10025,"该企业用户没有分配邮箱"), MAIL_REACH_MAX(10026,"达到收取邮箱上限"), MAIL_NEW_NOTEXIST(10027,"邮箱中没有可导入的简历"), PWD_CONFIRM_ERROR(10029,"两次密码不一致"), PWD_ERROR(10030,"密码不正确"), ENTER_OR_TALENT_NOT_EXITS(10028,"企业或人才库简历不存在"), PHONE_EMPTY(10031, "手机号不能为空"), EMAIL_EMPTY(10032, "邮箱不能为空"), NO_USABLE_MAIL(10040,"没有可用邮箱"), DEVICE_ID_EMPTY(10052,"设备ID:deviceId不能为空"), DELETE_CONNECT_ERROR(10053,"删除connect出错"); private int code; private String message; ResultCode(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } }
ApiException.java
、DefinitException.java
、JWTAuthenticationEntryPoint.java
、ExceptionControllerAdvice.java
、SimpleAccessDeniedHandler.java
、SimpleAuthenticationEntryPoint.java
、 :自定义异常类,用于全局异常处理。package com.baba.security.common.exception; import lombok.Getter; /** * @Author wulongbo * @Date 2021/10/27 11:58 * @Version 1.0 * 自定义异常 */ @Getter //只要getter方法,无需setter public class ApiException extends RuntimeException { private int code; private String msg; public ApiException() { this(1001, "接口错误"); } public ApiException(String msg) { this(1001, msg); } public ApiException(int code, String msg) { super(msg); this.code = code; this.msg = msg; } }
package com.baba.security.common.exception;
import com.baba.security.common.enums.ResultCode;
import lombok.Data;
/**
* @Author wulongbo
* @Date 2021/10/28 11:28
* @Version 1.0
*/
@Data
public class DefinitException extends RuntimeException {
private ResultCode resultCode;
private int code;
private String msg;
public DefinitException() {
this(1001, "接口错误");
}
public DefinitException(ResultCode resultCode) {
this(resultCode.getCode(), resultCode.getMessage());
this.resultCode=resultCode;
}
public DefinitException(int code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
}
package com.baba.security.common.exception;
import com.baba.security.common.enums.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
* @Author wulongbo
* @Date 2021/11/2 17:08
* @Version 1.0
*/
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
HashMap map = new HashMap<>(3);
map.put("uri", request.getRequestURI());
map.put("code", ResultCode.REQUEST_URL_WRONG.getCode());
map.put("msg", ResultCode.REQUEST_URL_WRONG.getMessage());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(new ObjectMapper().writeValueAsString(map));
}
}
package com.baba.security.common.handler;
import com.baba.security.common.enums.ResultCode;
import com.baba.security.common.exception.ApiException;
import com.baba.security.common.exception.DefinitException;
import com.baba.security.common.vo.ResultVO;
import io.jsonwebtoken.JwtException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @Author wulongbo
* @Date 2021/10/27 12:00
* @Version 1.0
* 全局异常控制类
*/
@RestControllerAdvice
public class ExceptionControllerAdvice {
@ExceptionHandler(DefinitException.class)
public ResultVO handleDefinitException(DefinitException e) {
// 注意哦,这里返回类型是自定义响应体
return new ResultVO<>(e.getResultCode());
}
@ExceptionHandler(ApiException.class)
public ResultVO handleApiException(ApiException e) {
// 注意哦,这里返回类型是自定义响应体
return new ResultVO<>(ResultCode.FAILED, e.getMsg());
}
@ExceptionHandler(JwtException.class)
public ResultVO handleJwtException(JwtException e) {
return new ResultVO<>(ResultCode.SAFETY_INVALID);
}
}
package com.baba.security.common.handler;
import com.baba.security.common.enums.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
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;
/**
* @Author wulongbo
* @Date 2021/10/28 13:49
* @Version 1.0
*/
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
//todo your business
HashMap map = new HashMap<>(3);
map.put("uri", request.getRequestURI());
map.put("code", ResultCode.REQUEST_BLANK.getCode());
map.put("msg", ResultCode.REQUEST_BLANK.getMessage());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper objectMapper = new ObjectMapper();
String resBody = objectMapper.writeValueAsString(map);
PrintWriter printWriter = response.getWriter();
printWriter.print(resBody);
printWriter.flush();
printWriter.close();
// throw new DefinitException(ResultCode.REQUEST_BLANK);
}
}
package com.baba.security.common.handler;
import com.baba.security.common.enums.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
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;
/**
* @Author wulongbo
* @Date 2021/10/28 13:49
* @Version 1.0
*/
public class SimpleAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
HashMap map = new HashMap<>(2);
map.put("uri", request.getRequestURI());
map.put("code", ResultCode.USER_AUTH_FAILD.getCode());
map.put("msg", ResultCode.USER_AUTH_FAILD.getMessage());
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
ObjectMapper objectMapper = new ObjectMapper();
String resBody = objectMapper.writeValueAsString(map);
PrintWriter printWriter = response.getWriter();
printWriter.print(resBody);
printWriter.flush();
printWriter.close();
}
}
这里就是工具类啦,直接贴不再说明。
package com.baba.security.common.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import java.time.Instant; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class JwtUtils { public static final String TOKEN_HEADER = "token"; public static final String TOKEN_PREFIX = "Bearer "; private static final String SUBJECT = "mayikt"; private static final long EXPIRITION = 1000 * 24 * 60 * 60 * 7; private static final String APPSECRET_KEY = "secret"; private static final String ROLE_CLAIMS = "roles"; private static final String LANGUAGE = "language"; public static String generateJsonWebToken(Authentication auth,String secretKey,String language) { Instant now = Instant.now(); String token = Jwts.builder() .setSubject(auth.getName()) .claim(LANGUAGE,language) .claim(ROLE_CLAIMS, auth.getAuthorities().stream() .map(GrantedAuthority::getAuthority).collect(Collectors.toList())) .setIssuedAt(Date.from(now)) .setExpiration(Date.from(now.plusSeconds(EXPIRITION))) .signWith(SignatureAlgorithm.HS256, secretKey.getBytes()) .compact(); return token; } /** * 生成token * * @param username * @param role * @return */ public static String createToken(String username, String role) { Map
map = new HashMap<>(); map.put(ROLE_CLAIMS, role); String token = Jwts .builder() .setSubject(username) .setClaims(map) .claim("username", username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRITION)) .signWith(SignatureAlgorithm.HS256, APPSECRET_KEY).compact(); return token; } public static Claims checkJWT(String token) { try { final Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody(); return claims; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 获取用户名 * * @param token * @return */ public static String getUsername(String token, String secretKey) { Claims claims = Jwts.parser() .setSigningKey(secretKey.getBytes()) .parseClaimsJws(token) .getBody(); String username = claims.getSubject(); return username; } /** * 获取用户角色 * * @param token * @return */ public static List getUserRole(String token, String secretKey) { Claims claims = Jwts.parser() .setSigningKey(secretKey.getBytes()) .parseClaimsJws(token) .getBody(); List authorities = claims.get(ROLE_CLAIMS, List.class); return authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); } /** * 获取用户角色 * * @param token * @return */ public static List getUserRole2(String token) { Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY.getBytes()).parseClaimsJws(token).getBody(); List authorities = claims.get("authorities", List.class); List roles = authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList()); return roles; } /** * 是否过期 * * @param token * @return */ public static boolean isExpiration(String token) { Claims claims = Jwts.parser().setSigningKey(APPSECRET_KEY).parseClaimsJws(token).getBody(); return claims.getExpiration().before(new Date()); } }
package com.baba.security.common.utils;
import java.security.MessageDigest;
public class MD5Util {
private static final String SALT = "mayikt";
public static String encode(String password) {
password = password + SALT;
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static void main(String[] args) {
System.out.println(MD5Util.encode("123456"));
}
}
package com.baba.security.common.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private StringRedisTemplate redisTemplate;
public void setRedisTemplate(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public StringRedisTemplate getRedisTemplate() {
return this.redisTemplate;
}
/** -------------------key相关操作--------------------- */
/**
* 删除key
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* 批量删除key
*
* @param keys
*/
public void delete(Collection keys) {
redisTemplate.delete(keys);
}
/**
* 序列化key
*
* @param key
* @return
*/
public byte[] dump(String key) {
return redisTemplate.dump(key);
}
/**
* 是否存在key
*
* @param key
* @return
*/
public Boolean hasKey(String key) {
return redisTemplate.hasKey(key);
}
/**
* 设置过期时间
*
* @param key
* @param timeout
* @param unit
* @return
*/
public Boolean expire(String key, long timeout, TimeUnit unit) {
return redisTemplate.expire(key, timeout, unit);
}
/**
* 设置过期时间
*
* @param key
* @param date
* @return
*/
public Boolean expireAt(String key, Date date) {
return redisTemplate.expireAt(key, date);
}
/**
* 查找匹配的key
*
* @param pattern
* @return
*/
public Set keys(String pattern) {
return redisTemplate.keys(pattern);
}
/**
* 将当前数据库的 key 移动到给定的数据库 db 当中
*
* @param key
* @param dbIndex
* @return
*/
public Boolean move(String key, int dbIndex) {
return redisTemplate.move(key, dbIndex);
}
/**
* 移除 key 的过期时间,key 将持久保持
*
* @param key
* @return
*/
public Boolean persist(String key) {
return redisTemplate.persist(key);
}
/**
* 返回 key 的剩余的过期时间
*
* @param key
* @param unit
* @return
*/
public Long getExpire(String key, TimeUnit unit) {
return redisTemplate.getExpire(key, unit);
}
/**
* 返回 key 的剩余的过期时间
*
* @param key
* @return
*/
public Long getExpire(String key) {
return redisTemplate.getExpire(key);
}
/**
* 从当前数据库中随机返回一个 key
*
* @return
*/
public String randomKey() {
return redisTemplate.randomKey();
}
/**
* 修改 key 的名称
*
* @param oldKey
* @param newKey
*/
public void rename(String oldKey, String newKey) {
redisTemplate.rename(oldKey, newKey);
}
/**
* 仅当 newkey 不存在时,将 oldKey 改名为 newkey
*
* @param oldKey
* @param newKey
* @return
*/
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
/**
* 返回 key 所储存的值的类型
*
* @param key
* @return
*/
public DataType type(String key) {
return redisTemplate.type(key);
}
/** -------------------string相关操作--------------------- */
/**
* 设置指定 key 的值
*
* @param key
* @param value
*/
public void set(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 获取指定 key 的值
*
* @param key
* @return
*/
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
/**
* 返回 key 中字符串值的子字符
*
* @param key
* @param start
* @param end
* @return
*/
public String getRange(String key, long start, long end) {
return redisTemplate.opsForValue().get(key, start, end);
}
/**
* 将给定 key 的值设为 value ,并返回 key 的旧值(old value)
*
* @param key
* @param value
* @return
*/
public String getAndSet(String key, String value) {
return redisTemplate.opsForValue().getAndSet(key, value);
}
/**
* 对 key 所储存的字符串值,获取指定偏移量上的位(bit)
*
* @param key
* @param offset
* @return
*/
public Boolean getBit(String key, long offset) {
return redisTemplate.opsForValue().getBit(key, offset);
}
/**
* 批量获取
*
* @param keys
* @return
*/
public List multiGet(Collection keys) {
return redisTemplate.opsForValue().multiGet(keys);
}
/**
* 设置ASCII码, 字符串'a'的ASCII码是97, 转为二进制是'01100001', 此方法是将二进制第offset位值变为value
*
* @param key 位置
* @param value 值,true为1, false为0
* @return
*/
public boolean setBit(String key, long offset, boolean value) {
return redisTemplate.opsForValue().setBit(key, offset, value);
}
/**
* 将值 value 关联到 key ,并将 key 的过期时间设为 timeout
*
* @param key
* @param value
* @param timeout 过期时间
* @param unit 时间单位, 天:TimeUnit.DAYS 小时:TimeUnit.HOURS 分钟:TimeUnit.MINUTES
* 秒:TimeUnit.SECONDS 毫秒:TimeUnit.MILLISECONDS
*/
public void setEx(String key, String value, long timeout, TimeUnit unit) {
redisTemplate.opsForValue().set(key, value, timeout, unit);
}
/**
* 只有在 key 不存在时设置 key 的值
*
* @param key
* @param value
* @return 之前已经存在返回false, 不存在返回true
*/
public boolean setIfAbsent(String key, String value) {
return redisTemplate.opsForValue().setIfAbsent(key, value);
}
/**
* 用 value 参数覆写给定 key 所储存的字符串值,从偏移量 offset 开始
*
* @param key
* @param value
* @param offset 从指定位置开始覆写
*/
public void setRange(String key, String value, long offset) {
redisTemplate.opsForValue().set(key, value, offset);
}
/**
* 获取字符串的长度
*
* @param key
* @return
*/
public Long size(String key) {
return redisTemplate.opsForValue().size(key);
}
/**
* 批量添加
*
* @param maps
*/
public void multiSet(Map maps) {
redisTemplate.opsForValue().multiSet(maps);
}
/**
* 同时设置一个或多个 key-value 对,当且仅当所有给定 key 都不存在
*
* @param maps
* @return 之前已经存在返回false, 不存在返回true
*/
public boolean multiSetIfAbsent(Map maps) {
return redisTemplate.opsForValue().multiSetIfAbsent(maps);
}
/**
* 增加(自增长), 负数则为自减
*
* @param key
* @return
*/
public Long incrBy(String key, long increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
/**
* @param key
* @return
*/
public Double incrByFloat(String key, double increment) {
return redisTemplate.opsForValue().increment(key, increment);
}
/**
* 追加到末尾
*
* @param key
* @param value
* @return
*/
public Integer append(String key, String value) {
return redisTemplate.opsForValue().append(key, value);
}
/** -------------------hash相关操作------------------------- */
/**
* 获取存储在哈希表中指定字段的值
*
* @param key
* @param field
* @return
*/
public T hGet(String key, String field) {
return (T)redisTemplate.opsForHash().get(key, field);
}
/**
* 获取所有给定字段的值
*
* @param key
* @return
*/
public Map
package com.baba.security.common.utils;
import java.util.Random;
/**
* @Author wulongbo
* @Date 2021/10/25 15:54
* @Version 1.0
*/
public class SaltUtils {
/**
* 生成salt的静态方法
*/
public static String getSalt(int n) {
char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~!@#$%^&*()_+".toCharArray();
int length = chars.length;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++) {
char achar = chars[new Random().nextInt(length)];
sb.append(achar);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(getSalt(8));
}
}
package com.baba.security.common.utils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Locale;
/**
* @Author wulongbo
* @Date 2021/11/2 17:21
* @Version 1.0
*/
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
// 设置上下文
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if (SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = applicationContext;
}
}
//获取上下文
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通过名字获取上下文的Bean
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
//通过类型获取上下文的bean
public static T getBean(Class clazz) {
return getApplicationContext().getBean(clazz);
}
public static T getBean(String name, Class clazz) {
return getApplicationContext().getBean(name, clazz);
}
// 国际化使用
public static String getMessage(String key) {
return applicationContext.getMessage(key, null, Locale.getDefault());
}
// 获取当前环境
public static String[] getActiveProfiles() {
return applicationContext.getEnvironment().getActiveProfiles();
}
// 判断当前环境是否为test/local
public static boolean isDevEnv() {
String[] activeProfiles = getActiveProfiles();
if (activeProfiles.length < 1) {
return false;
}
for (String activeProfile : activeProfiles) {
if (StringUtils.equals(activeProfile, "dev")) {
return true;
}
}
return false;
}
}
VO响应对象
package com.baba.security.common.vo; import com.baba.security.common.enums.ResultCode; import lombok.Data; /** * @Author wulongbo * @Date 2021/10/27 14:18 * @Version 1.0 */ @Data public class ResultVO
{ /** * 状态码,比如1000代表响应成功 */ private int code; /** * 响应信息,用来说明响应情况 */ private String msg; /** * 响应的具体数据 */ private T data; public ResultVO(T data) { this(ResultCode.SUCCESS,data); } public ResultVO(ResultCode resultCode, T data) { this.code = resultCode.getCode(); this.msg = resultCode.getMessage(); this.data = data; } public ResultVO(ResultCode resultCode) { this.code = resultCode.getCode(); this.msg = resultCode.getMessage(); } } 自此 common模块就写完成,后面我们来完成登录认证模块