在微服务分布框架下经常会有多台tomcat,用户的登录信息如何存储就成为了一个问题,下面看看解决方法
通过配置session来实现session复制,保证每台服务器上都存在着用户的登录信息
通过增加缓存组件来实现,将用户信息存放到缓存组件中
使用JWT来实现客户端存储
微服务认证方案设计
为防止密钥泄露可以将对应信息配置在nacos中
JWT
作用
基于JJWT实现微服务JWT授权
JJWT是一个对JWT进行封装的类库,可以通过其提供的api轻松的进行调用。
依赖
<!-- jjwt所需的依赖 -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
<version>0.11.2</version>
<scope>runtime</scope>
</dependency>
生成jwt令牌
@Test
public void jwtAuth(){
// 自定义一个密钥
String key = "cereshuzhitingnizhenbangcereshuzhitingnizhenbang";
// 对密钥进行base64编码
String base64Key = new BASE64Encoder().encode(key.getBytes());
// 生成密钥对象,会根据base64长度自动选择相应的 HMAC 算法
SecretKey secretKey = Keys.hmacShaKeyFor(base64Key.getBytes());
// 利用jjwt生成tocken
String jwt = Jwts.builder()
//.setSubject:是jwt中载荷部分的内容
.setSubject("{\"userId\":123}")
.signWith(secretKey).compact();
String jws = Jwts.builder().setSubject("Joe").signWith(secretKey).compact();
System.out.println(jws);
}
基于JJWT构建认证服务
下面我们从业务中加入jwt认证,即在用户登录成功后在用户信息中加入对应的token信息
vo类
package com.guming.vo;
public class ResponseCode<T> {
private String code;
private String message;
private T date;
public ResponseCode(T... data) {
this.code = "200";
this.message = "执行成功";
if(data.length > 0){
this.date = data[0];
}
}
public ResponseCode(String code, String message) {
this.code = code;
this.message = message;
}
public ResponseCode(String code, String message, T date) {
this.code = code;
this.message = message;
this.date = date;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getDate() {
return date;
}
public void setDate(T date) {
this.date = date;
}
}
mapper类,采用mybatis-plus框架来查询数据库
package com.guming.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.guming.entiry.AuthEntiry;
import org.springframework.stereotype.Repository;
/**
* 身份验证映射器
*
* @author 先生
* @date 2021/01/25
*/
@Repository
public interface AuthMapper extends BaseMapper<AuthEntiry> {
}
service类
package com.guming.service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guming.entiry.AuthEntiry;
import com.guming.mapper.AuthMapper;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
public class AuthService {
@Autowired
private AuthMapper authMapper;
public AuthEntiry findUserByUserAndPassword(String userName,String password){
QueryWrapper<AuthEntiry> wrapper = new QueryWrapper();
wrapper.eq(!StringUtils.isEmpty(userName),"user_name",userName)
.eq(!StringUtils.isEmpty(password),"pass_word",password);
AuthEntiry authEntiry = authMapper.selectOne(wrapper);
if(authEntiry == null){
throw new SecurityException("用户名或密码错误");
}
return authEntiry;
}
}
controller类
package com.guming.controller;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guming.entiry.AuthEntiry;
import com.guming.service.AuthService;
import com.guming.vo.ResponseCode;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.crypto.SecretKey;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AuthController {
@Autowired
private AuthService authService;
@Value("${app.auth.secretKey}")
private String appKey;
@PostMapping("/auth")
public ResponseCode<Map>auth(String userName,String password){
ResponseCode<Map> responseCode = null;
try {
AuthEntiry user = authService.findUserByUserAndPassword(userName, password);
Map date = new HashMap();
date.put("user",user);
responseCode = new ResponseCode<>(date);
// 对密钥进行base64编码
String base64Key = new BASE64Encoder().encode(appKey.getBytes());
// 生成密钥对象,会根据base64长度自动选择相应的 HMAC 算法
SecretKey secretKey = Keys.hmacShaKeyFor(base64Key.getBytes());
// 将用户实体进行json转化
ObjectMapper mapper = new ObjectMapper();
// 将不为空的属性转化为json
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String userJson = mapper.writeValueAsString(user);
// 利用jjwt生成tocken
String jwtToken = Jwts.builder()
.setSubject(userJson)
.signWith(secretKey).compact();
date.put("token",jwtToken);
}catch (Exception e){
e.printStackTrace();
// getSimpleName() 得到异常的方法信息
responseCode = new ResponseCode<>(e.getClass().getSimpleName(),e.getMessage());
}
return responseCode;
}
}
配置信息
server:
port: 8004
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/cloud_admin_v1?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: 123456
application:
name: manage-auth
cloud:
nacos:
discovery:
username: nacos
password: nacos
server-addr: 127.0.0.1:8848
namespace: public # 注册到 nacos 的指定 namespace,默认为 public
# 属性为空时该属性不会被转换成json
jackson:
default-property-inclusion: non_null
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 显示sql语句等信息
#jwt自定义密钥
app:
auth:
secretKey: 1234567890-1234567890-1234567890
数据库对应表
效果
解析对应token
@Test
public void check(){
String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJ1c2VySWRcIjoxLFwidXNlck5hbWVcIjpcInpoYW5nU2FuXCIsXCJwYXNzV29yZFwiOlwiMTIzNDU2XCIsXCJuYW1lXCI6XCLlvKDkuIlcIixcImdyYWRlXCI6XCJub3JtYWxcIn0ifQ.ggGAr5qo9ZWA5BFdFktcv6aaILhOsCj6yh-ftuVY8_Y";
// 自定义一个密钥
String key = "1234567890-1234567890-1234567890";
// 对密钥进行base64编码
String base64Key = new BASE64Encoder().encode(key.getBytes());
// 生成密钥对象,会根据base64长度自动选择相应的 HMAC 算法
SecretKey secretKey = Keys.hmacShaKeyFor(base64Key.getBytes());
// 验证tocken
JwtParser build = Jwts.parserBuilder().setSigningKey(secretKey).build();
Jws<Claims> claimsJws = build.parseClaimsJws(jwt);
// 从tocken中解析出用户信息
String subject = claimsJws.getBody().getSubject();
System.out.println(subject);
}
通过注解实现通用JWT校验
即在需要进行jwt校验的方法前加上自定义的注解,说明需要进行校验,然后该注解会自动去进行校验,通过才执行对应的方法,不通过返回异常信息
业务逻辑:
- 在请求方法上加上@JwtToken注解后表示该方法需要进行token校验,@JwtToken(required = false)表示该请求头中没有token信息也可以进行访问;如果为true就表示必须要有token,如果没有就报错误异常。
- 拦截器会对所有方法进行拦截,检查@JwtToken是不是必须要有,同时对token进行解析,从token中获得用户信息,并将用户信息放入session中给请求的接口使用
- 在请求的api中对用户角色进行判断,针对不同的角色进行返回不同的资源。
1.自定义注解
package com.guming.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// ElementType.TYPE:接口、类、枚举上可以使用
@Target({ElementType.METHOD,ElementType.TYPE})
// 运行时注解生效
@Retention(RetentionPolicy.RUNTIME)
public @interface JwtToken {
// 该属性的意思是:当required=true说明请求头中必须包含token,否则报错
// 当required=false 说明请求头中不是必须包含token,没有token也可以调用对应的接口
boolean required() default true;
}
拦截器设计
package com.guming.interceptor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guming.annotation.JwtToken;
import com.guming.entiry.AuthEntiry;
import com.guming.vo.ResponseCode;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import sun.misc.BASE64Encoder;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* 令牌拦截器
* 执行目标URL方法前,对存放在请求头中的jwt进行校验,检验通过执行目标方法,校验失败则提示错误
* @author 先生
* @date 2021/01/25
*/
public class TokenInterceptor implements HandlerInterceptor {
@Value("${app.auth.secretKey}")
private String appKey = null;
// 方法执行前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 如果不是映射到方法就直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
// 通过反射获得到请求对应的方法
Method method = handlerMethod.getMethod();
// 设置响应格式
response.setContentType("text/json;charset=utf-8");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 判断目标方法是否包含JwtToken注解
if(method.isAnnotationPresent(JwtToken.class)){
// 从请求头中获取token值
String token = request.getHeader("token");
if(token == null){
// 获取到JwtToken注解的信息
JwtToken jwtToken = method.getAnnotation(JwtToken.class);
// 当required=true说明请求头中必须包含token,否则报错
if(jwtToken.required() == true) {
// 401 表示未认证
response.setStatus(401);
ResponseCode responseCode = new ResponseCode("AuthException", "非法请求,校验未通过");
String json = objectMapper.writeValueAsString(responseCode);
// 将异常信息返回给前端
response.getWriter().println(json);
return false;
}
}else { //token 存在时校验JWT的有效性
// 对密钥进行base64编码
String base64Key = new BASE64Encoder().encode(appKey.getBytes());
// 生成密钥对象,会根据base64长度自动选择相应的 HMAC 算法
SecretKey secretKey = Keys.hmacShaKeyFor(base64Key.getBytes());
// 验证tocken
try {
Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token);
// 获取token中的用户信息
String userJson = claimsJws.getBody().getSubject();
System.out.println(userJson);
// 将token中的用户信息反序列化成用户对象
AuthEntiry authEntiry = objectMapper.readValue(userJson, AuthEntiry.class);
// 将用户信息放入session中,对应的接口就可以获取到用户信息
request.setAttribute("$user",authEntiry);
}catch (JwtException e){
e.printStackTrace();
// 401 表示未认证
response.setStatus(401);
ResponseCode responseCode = new ResponseCode(e.getClass().getSimpleName(),"token错误,校验未通过");
String json = objectMapper.writeValueAsString(responseCode);
// 将异常信息返回给前端
response.getWriter().println(json);
return false;
}
}
}
// 返回false为拦截成功,返回异常信息,不会去执行对应的请求
return true;
}
}
将拦截器放入spring进行管理
package com.guming.config;
import com.guming.interceptor.TokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class AuthConfig implements WebMvcConfigurer {
// 在Spring ioc 容器启动时将TokenInterceptor对象放入ioc进行管理
@Bean
public TokenInterceptor tokenInterceptor(){
return new TokenInterceptor();
}
// 添加拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加对应的拦截器,并且设置对应的拦截路径 /**为拦截全部
registry.addInterceptor(tokenInterceptor()).addPathPatterns("/**");
}
}
控制器
package com.guming.controller;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.guming.annotation.JwtToken;
import com.guming.entiry.AuthEntiry;
import com.guming.service.AuthService;
import com.guming.vo.ResponseCode;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.crypto.SecretKey;
import java.util.HashMap;
import java.util.Map;
@RestController
public class AuthController {
@Autowired
private AuthService authService;
@Value("${app.auth.secretKey}")
private String appKey;
@PostMapping("/auth")
public ResponseCode<Map>auth(String userName,String password){
ResponseCode<Map> responseCode = null;
try {
AuthEntiry user = authService.findUserByUserAndPassword(userName, password);
Map date = new HashMap();
date.put("user",user);
responseCode = new ResponseCode<>(date);
// 对密钥进行base64编码
String base64Key = new BASE64Encoder().encode(appKey.getBytes());
// 生成密钥对象,会根据base64长度自动选择相应的 HMAC 算法
SecretKey secretKey = Keys.hmacShaKeyFor(base64Key.getBytes());
// 将用户实体进行json转化
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
String userJson = mapper.writeValueAsString(user);
// 利用jjwt生成tocken;setSubject:里面存放用户信息,注意格式时json
String jwtToken = Jwts.builder()
.setSubject(userJson)
.signWith(secretKey).compact();
date.put("token",jwtToken);
}catch (Exception e){
e.printStackTrace();
// getSimpleName() 得到异常的方法信息
responseCode = new ResponseCode<>(e.getClass().getSimpleName(),e.getMessage());
}
return responseCode;
}
/**
* @Author:
* @Description:
* @Date: 17:21 2021/1/25
* @Param: @RequestAttribute(name = "$user",required = false) 就相当于 request.getAttribute("user");
* required = false: 意思是缓存中可以不包含用户信息
* @return:
*/
@RequestMapping("/authTest")
@JwtToken(required = false)
public ResponseCode authTest(@RequestAttribute(name = "$user",required = false)AuthEntiry authEntiry){
if(authEntiry == null){
return new ResponseCode("普通用户,返回普通信息");
}else if(authEntiry.getGrade().equals("normal")){
return new ResponseCode("普通用户,返回普通信息");
}else if(authEntiry.getGrade().equals("vip")){
return new ResponseCode("vip用户,返回vip信息");
}
return new ResponseCode("发生异常,请联系管理员");
}
}
调用方式
先通过 /auth 接口进行用户登录,并获取到对应的token
然后在调用 /authTest 并在请求头中设置token信息