java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringCloud JWT认证和鉴权

详解用JWT对SpringCloud进行认证和鉴权

作者:慕容千语

这篇文章主要介绍了详解用JWT对SpringCloud进行认证和鉴权,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

JWT(JSON WEB TOKEN)是基于RFC 7519标准定义的一种可以安全传输的小巧和自包含的JSON对象。由于数据是使用数字签名的,所以是可信任的和安全的。JWT可以使用HMAC算法对secret进行加密或者使用RSA的公钥私钥对来进行签名。

JWT通常由头部(Header),负载(Payload),签名(Signature)三个部分组成,中间以.号分隔,其格式为Header.Payload.Signature

Header:声明令牌的类型和使用的算法

Payload:也称为JWT Claims,包含用户的一些信息

系统保留的声明(Reserved claims):

公共的声明(public):见 http://www.iana.org/assignments/jwt/jwt.xhtml

私有的声明(private claims):根据业务需要自己定义的数据

Signature:签名

签名格式: HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)

JWT的特点:

认证原理:

JWT的使用方式:一种做法是放在HTTP请求的头信息Authorization字段里面,格式如下:

Authorization: <token>

 需要将服务器设置为接受来自所有域的请求,用Access-Control-Allow-Origin: *

  另一种做法是,跨域的时候,JWT就放在POST请求的数据体里面。

对JWT实现token续签的做法:

1、额外生成一个refreshToken用于获取新token,refreshToken需存储于服务端,其过期时间比JWT的过期时间要稍长。

2、用户携带refreshToken参数请求token刷新接口,服务端在判断refreshToken未过期后,取出关联的用户信息和当前token。

3、使用当前用户信息重新生成token,并将旧的token置于黑名单中,返回新的token。

创建用于登录认证的工程auth-service:

1、 创建pom.xml文件

<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/maven-v4_0_0.xsd"> 
 <modelVersion>4.0.0</modelVersion> 
 <groupId>com.seasy.springcloud</groupId> 
 <artifactId>auth-service</artifactId> 
 <version>1.0.0</version> 
 <packaging>jar</packaging> 
  
 <parent> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-parent</artifactId> 
  <version>2.0.8.RELEASE</version> 
  <relativePath/> 
 </parent> 
 
 <properties> 
  <java.version>1.8</java.version> 
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
 </properties> 
  
 <dependencies> 
  <dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId> 
  </dependency> 
  <dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-actuator</artifactId> 
  </dependency> 
   
  <!-- spring cloud --> 
  <dependency> 
    <groupId>org.springframework.cloud</groupId> 
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> 
  </dependency> 
   
  <!-- redis --> 
  <dependency> 
    <groupId>org.springframework.boot</groupId> 
    <artifactId>spring-boot-starter-data-redis</artifactId> 
  </dependency> 
  <dependency> 
    <groupId>org.apache.commons</groupId> 
    <artifactId>commons-pool2</artifactId> 
  </dependency> 
   
  <!-- jwt --> 
  <dependency> 
    <groupId>com.auth0</groupId> 
    <artifactId>java-jwt</artifactId> 
    <version>3.7.0</version> 
  </dependency> 
 </dependencies> 
  
 <dependencyManagement> 
  <dependencies> 
    <dependency> 
      <groupId>org.springframework.cloud</groupId> 
      <artifactId>spring-cloud-dependencies</artifactId> 
      <version>Finchley.RELEASE</version> 
      <type>pom</type> 
      <scope>import</scope> 
    </dependency> 
  </dependencies> 
 </dependencyManagement> 
</project> 

2、JWT工具类

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、LoginController类

@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、application配置信息

spring.application.name=auth-service 
server.port=4040 
 
eureka.instance.hostname=${spring.cloud.client.ip-address} 
eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port} 
eureka.instance.prefer-ip-address=true 
 
eureka.client.service-url.defaultZone=http://root:123456@${eureka.instance.hostname}:7001/eureka/ 
 
#redis 
spring.redis.database=0 
spring.redis.timeout=3000ms 
spring.redis.lettuce.pool.max-active=100 
spring.redis.lettuce.pool.max-wait=-1ms 
spring.redis.lettuce.pool.min-idle=0 
spring.redis.lettuce.pool.max-idle=8 
 
#standalone 
spring.redis.host=192.168.134.134 
spring.redis.port=7001 
 
#sentinel 
#spring.redis.sentinel.master=mymaster 
#spring.redis.sentinel.nodes=192.168.134.134:26379,192.168.134.134:26380 

5、启动类

@SpringBootApplication 
@EnableEurekaClient 
public class Main{ 
  public static void main(String[] args){ 
    SpringApplication.run(Main.class, args); 
  } 
} 

改造SpringCloud Gateway工程

1、在pom.xml文件添加依赖

<!-- redis --> 
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-data-redis</artifactId> 
</dependency> 
<dependency> 
  <groupId>org.apache.commons</groupId> 
  <artifactId>commons-pool2</artifactId> 
</dependency> 
 
<!-- jwt --> 
<dependency> 
  <groupId>com.auth0</groupId> 
  <artifactId>java-jwt</artifactId> 
  <version>3.7.0</version> 
</dependency>

2、创建全局过滤器JWTAuthFilter

@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); 
  } 
} 

3、关键的application配置信息

spring: 
 application: 
  name: service-gateway 
 cloud: 
  gateway: 
   discovery: 
    locator: 
     enabled: true 
     lowerCaseServiceId: true 
   routes: 
    #认证服务路由 
    - id: auth-service 
     predicates: 
      - Path=/auth-service/** 
     uri: lb://auth-service 
     filters: 
      - StripPrefix=1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文