微服务登录

JWTtoken 微服务登录安全验证

		1、添加maven 依赖  
 	<dependency>  
        <groupId>com.auth0</groupId>  
        <artifactId>java-jwt</artifactId>  
        <version>3.7.0</version>  
    </dependency>  
  二  编写工具类
public class JWTUtil {  
    public static final String SECRET_KEY = "123456"; //秘钥  
    public static final long TOKEN_EXPIRE_TIME = 5 * 60 * 1000; //token过期时间  
    public static final long REFRESH_TOKEN_EXPIRE_TIME = 10 * 60 * 1000; //refreshToken过期时间  
    private static final String ISSUER = "issuer"; //签发人  
  
    /** 
     * 生成签名 
     */  
    public static String generateToken(String username){  
        Date now = new Date();  
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法  
          
        String token = JWT.create()  
            .withIssuer(ISSUER) //签发人  
            .withIssuedAt(now) //签发时间  
            .withExpiresAt(new Date(now.getTime() + TOKEN_EXPIRE_TIME)) //过期时间  
            .withClaim("username", username) //保存身份标识  
            .sign(algorithm);  
        return token;  
    }  
      
    /** 
     * 验证token 
     */  
    public static boolean verify(String token){  
        try {  
            Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); //算法  
            JWTVerifier verifier = JWT.require(algorithm)  
                    .withIssuer(ISSUER)  
                    .build();  
            verifier.verify(token);  
            return true;  
        } catch (Exception ex){  
            ex.printStackTrace();  
        }  
        return false;  
    }  
      
    /** 
     * 从token获取username 
     */  
    public static String getUsername(String token){  
        try{  
            return JWT.decode(token).getClaim("username").asString();  
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
        return "";  
    }  
}  
 3 登录业务实现
@RestController  
public class LoginController {  
    @Autowired  
    StringRedisTemplate redisTemplate;  
      
    /** 
     * 登录认证 
     * @param username 用户名 
     * @param password 密码 
     */  
    @GetMapping("/login")  
    public AuthResult login(@RequestParam String username, @RequestParam String password) {  
        if("admin".equals(username) && "admin".equals(password)){  
            //生成token  
            String token = JWTUtil.generateToken(username);  
              
            //生成refreshToken  
            String refreshToken = StringUtil.getUUIDString();  
              
            //数据放入redis  
            redisTemplate.opsForHash().put(refreshToken, "token", token);  
            redisTemplate.opsForHash().put(refreshToken, "username", username);  
              
            //设置token的过期时间  
            redisTemplate.expire(refreshToken, JWTUtil.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.MILLISECONDS);  
              
            return new AuthResult(0, "success", token, refreshToken);  
        }else{  
            return new AuthResult(1001, "username or password error");  
        }  
    }  
      
    /** 
     * 刷新token 
     */  
    @GetMapping("/refreshToken")  
    public AuthResult refreshToken(@RequestParam String refreshToken) {  
        String username = (String)redisTemplate.opsForHash().get(refreshToken, "username");  
        if(StringUtil.isEmpty(username)){  
            return new AuthResult(1003, "refreshToken error");  
        }  
  
        //生成新的token  
        String newToken = JWTUtil.generateToken(username);  
        redisTemplate.opsForHash().put(refreshToken, "token", newToken);  
        return new AuthResult(0, "success", newToken, refreshToken);  
    }  
  
    @GetMapping("/")  
    public String index() {  
        return "auth-service: " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));  
    }  
}  
4 创建全局的网关过滤器
@Component  
public class JWTAuthFilter implements GlobalFilter, Ordered{  
    @Override  
    public int getOrder() {  
        return -100;  
    }  
      
    @Override  
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {  
        String url = exchange.getRequest().getURI().getPath();  
          
        //忽略以下url请求  
        if(url.indexOf("/auth-service/") >= 0){  
            return chain.filter(exchange);  
        }  
          
        //从请求头中取得token  
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");  
        if(StringUtil.isEmpty(token)){  
            ServerHttpResponse response = exchange.getResponse();  
            response.setStatusCode(HttpStatus.OK);  
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");  
              
            Response res = new Response(401, "401 unauthorized");  
            byte[] responseByte = JSONObject.fromObject(res).toString().getBytes(StandardCharsets.UTF_8);  
              
            DataBuffer buffer = response.bufferFactory().wrap(responseByte);  
            return response.writeWith(Flux.just(buffer));  
        }  
          
        //请求中的token是否在redis中存在  
        boolean verifyResult = JWTUtil.verify(token);  
        if(!verifyResult){  
            ServerHttpResponse response = exchange.getResponse();  
            response.setStatusCode(HttpStatus.OK);  
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");  
  
            Response res = new Response(1004, "invalid token");  
            byte[] responseByte = JSONObject.fromObject(res).toString().getBytes(StandardCharsets.UTF_8);  
              
            DataBuffer buffer = response.bufferFactory().wrap(responseByte);  
            return response.writeWith(Flux.just(buffer));  
        }  
          
        return chain.filter(exchange);  
    }  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值