Java架构笔记:用JWT对SpringCloud进行认证和鉴权

写在前面

喜欢的朋友可以关注下专栏:Java架构技术进阶。里面有大量batj面试题集锦,还有各种技术分享,如有好文章也欢迎投稿哦。

image.png

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

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

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

   alg:签名的算法

typ:token的类型,比如JWT

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

   系统保留的声明(Reserved claims):
      iss <span class="token punctuation">(</span>issuer<span class="token punctuation">)</span>:签发人

      <span class="hljs-built_in">exp</span> <span class="token punctuation">(</span>expiration time<span class="token punctuation">)</span>:过期时间

      sub <span class="token punctuation">(</span>subject<span class="token punctuation">)</span>:主题

      aud <span class="token punctuation">(</span>audience<span class="token punctuation">)</span>:受众用户

      nbf <span class="token punctuation">(</span>Not Before<span class="token punctuation">)</span>:在此之前不可用

      iat <span class="token punctuation">(</span>Issued At<span class="token punctuation">)</span>:签发时间

      jti <span class="token punctuation">(</span>JWT ID<span class="token punctuation">)</span>:JWT唯一标识,能用于防止JWT重复使用

公共的声明(public)

      见 http<span class="token operator">:</span><span class="token operator"><span class="hljs-comment">/</span></span><span class="token operator"><span class="hljs-comment">/</span></span><span class="hljs-comment">www</span><span class="token punctuation"><span class="hljs-comment">.</span></span><span class="hljs-comment">iana</span><span class="token punctuation"><span class="hljs-comment">.</span></span><span class="hljs-comment">org</span><span class="token operator"><span class="hljs-comment">/</span></span><span class="hljs-comment">assignments</span><span class="token operator"><span class="hljs-comment">/</span></span><span class="hljs-comment">jwt</span><span class="token operator"><span class="hljs-comment">/</span></span><span class="hljs-comment">jwt</span><span class="token punctuation"><span class="hljs-comment">.</span></span><span class="hljs-comment">xhtml</span>

私有的声明(private claims)

      根据业务需要自己定义的数据

Signature:签名

   签名格式:
      HMACSHA256(base64UrlEncode(header) + <span class="hljs-string">"."</span> + base64UrlEncode(payload), secret)

JWT的特点:

  JWT默认是不加密的,不能把用户敏感类信息放在Payload部分。

JWT 不仅可以用于认证,也可以用于交换信息。

JWT的最大缺点是服务器不保存会话状态,所以在使用期间不可能取消令牌或更改令牌的权限。

JWT本身包含认证信息,为了减少盗用,JWT的有效期不宜设置太长。

为了减少盗用和窃取,JWT不建议使用HTTP协议来传输代码,而是使用加密的HTTPS协议进行传输。

首次生成token比较慢,比较耗CPU,在高并发的情况下需要考虑CPU占用问题。

生成的token比较长,可能需要考虑流量问题。

认证原理:

 客户端向服务器申请授权,服务器认证以后,生成一个token字符串并返回给客户端,此后客户端在请求
 受保护的资源时携带这个token,服务端进行验证再从这个token中解析出用户的身份信息。

JWT的使用方式:

  一种做法是放在HTTP请求的头信息Authorization字段里面,格式如下:
     Authorization<span class="token punctuation">:</span> <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="xml"><span class="hljs-tag">&lt;</span></span></span><span class="xml"><span class="hljs-tag"><span class="hljs-name">token</span></span></span></span><span class="token punctuation"><span class="xml"><span class="hljs-tag">&gt;</span></span></span></span><span class="token plain-text"><span class="xml">

     需要将服务器设置为接受来自所有域的请求,用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文件

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>

<span class="token comment"><span class="hljs-comment">&lt;!-- spring cloud --&gt;</span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>org.springframework.cloud<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>spring-cloud-starter-netflix-eureka-client<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
  
<span class="token comment"><span class="hljs-comment">&lt;!-- redis --&gt;</span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>org.springframework.boot<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>spring-boot-starter-data-redis<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>org.apache.commons<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>commons-pool2<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
  
<span class="token comment"><span class="hljs-comment">&lt;!-- jwt --&gt;</span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>com.auth0<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">groupId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>java-jwt<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">artifactId</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
    <span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;</span></span><span class="hljs-tag"><span class="hljs-name">version</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>3.7.0<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">version</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  
<span class="token tag"><span class="token tag"><span class="token punctuation"><span class="hljs-tag">&lt;/</span></span><span class="hljs-tag"><span class="hljs-name">dependency</span></span></span><span class="token punctuation"><span class="hljs-tag">&gt;</span></span></span>  

</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工具类

Java代码

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"; //签发人  
<span class="token comment">/** 
 * 生成签名 
 */</span>  
<span class="token keyword">public</span> <span class="token keyword">static</span> String <span class="token function">generateToken</span><span class="token punctuation">(</span><span class="token parameter">String username</span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
    Date now <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    Algorithm algorithm <span class="token operator">=</span> Algorithm<span class="token punctuation">.</span><span class="token constant">HMAC256</span><span class="token punctuation">(</span><span class="token constant">SECRET_KEY</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//算法  </span>
      
    String token <span class="token operator">=</span> <span class="token constant">JWT</span><span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span><span class="token punctuation">)</span>  
        <span class="token punctuation">.</span><span class="token function">withIssuer</span><span class="token punctuation">(</span><span class="token constant">ISSUER</span><span class="token punctuation">)</span> <span class="token comment">//签发人  </span>
        <span class="token punctuation">.</span><span class="token function">withIssuedAt</span><span class="token punctuation">(</span>now<span class="token punctuation">)</span> <span class="token comment">//签发时间  </span>
        <span class="token punctuation">.</span><span class="token function">withExpiresAt</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Date</span><span class="token punctuation">(</span>now<span class="token punctuation">.</span><span class="token function">getTime</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">+</span> <span class="token constant">TOKEN_EXPIRE_TIME</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment">//过期时间  </span>
        <span class="token punctuation">.</span><span class="token function">withClaim</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">,</span> username<span class="token punctuation">)</span> <span class="token comment">//保存身份标识  </span>
        <span class="token punctuation">.</span><span class="token function">sign</span><span class="token punctuation">(</span>algorithm<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token keyword">return</span> token<span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  
  
<span class="token comment">/** 
 * 验证token 
 */</span>  
<span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token builtin">boolean</span> <span class="token function">verify</span><span class="token punctuation">(</span><span class="token parameter">String token</span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
    <span class="token keyword">try</span> <span class="token punctuation">{</span>  
        Algorithm algorithm <span class="token operator">=</span> Algorithm<span class="token punctuation">.</span><span class="token constant">HMAC256</span><span class="token punctuation">(</span><span class="token constant">SECRET_KEY</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment">//算法  </span>
        JWTVerifier verifier <span class="token operator">=</span> <span class="token constant">JWT</span><span class="token punctuation">.</span><span class="token keyword">require</span><span class="token punctuation">(</span>algorithm<span class="token punctuation">)</span>  
                <span class="token punctuation">.</span><span class="token function">withIssuer</span><span class="token punctuation">(</span><span class="token constant">ISSUER</span><span class="token punctuation">)</span>  
                <span class="token punctuation">.</span><span class="token function">build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        verifier<span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>token<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span>Exception ex<span class="token punctuation">)</span><span class="token punctuation">{</span>  
        ex<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>  
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  
  
<span class="token comment">/** 
 * 从token获取username 
 */</span>  
<span class="token keyword">public</span> <span class="token keyword">static</span> String <span class="token function">getUsername</span><span class="token punctuation">(</span><span class="token parameter">String token</span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
    <span class="token keyword">try</span><span class="token punctuation">{</span>  
        <span class="token keyword">return</span> <span class="token constant">JWT</span><span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span>token<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getClaim</span><span class="token punctuation">(</span><span class="token string">"username"</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">asString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span><span class="token keyword">catch</span><span class="token punctuation">(</span>Exception ex<span class="token punctuation">)</span><span class="token punctuation">{</span>  
        ex<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>  
    <span class="token keyword">return</span> <span class="token string">""</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  

}

3、LoginController类

Java代码

  
public class LoginController {  
      
    StringRedisTemplate redisTemplate;  
<span class="token comment"><span class="hljs-comment"><span class="markdown">/** 

* 登录认证
* @param username 用户名
* @param password 密码
*/
("/login")
public AuthResult login( String username, String password) {
if("admin".equals(username) && "admin".equals(password)){
//生成token
String token = JWTUtil.generateToken(username);

        <span class="token comment"><span class="hljs-comment">//生成refreshToken  </span></span>
        <span class="hljs-built_in">String</span> refreshToken <span class="token operator">=</span> StringUtil<span class="token punctuation">.</span><span class="token function">getUUIDString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
          
        <span class="token comment"><span class="hljs-comment">//数据放入redis  </span></span>
        redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>refreshToken<span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"token"</span></span><span class="token punctuation">,</span> token<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>refreshToken<span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"username"</span></span><span class="token punctuation">,</span> username<span class="token punctuation">)</span><span class="token punctuation">;</span>  
          
        <span class="token comment"><span class="hljs-comment">//设置token的过期时间  </span></span>
        redisTemplate<span class="token punctuation">.</span><span class="token function">expire</span><span class="token punctuation">(</span>refreshToken<span class="token punctuation">,</span> JWTUtil<span class="token punctuation">.</span>REFRESH_TOKEN_EXPIRE_TIME<span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">)</span><span class="token punctuation">;</span>  
          
        <span class="token keyword"><span class="hljs-keyword">return</span></span> <span class="token keyword"><span class="hljs-keyword">new</span></span> <span class="token class-name">AuthResult</span><span class="token punctuation">(</span><span class="token number"><span class="hljs-number">0</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"success"</span></span><span class="token punctuation">,</span> token<span class="token punctuation">,</span> refreshToken<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span><span class="token keyword"><span class="hljs-keyword">else</span></span><span class="token punctuation">{</span>  
        <span class="token keyword"><span class="hljs-keyword">return</span></span> <span class="token keyword"><span class="hljs-keyword">new</span></span> <span class="token class-name">AuthResult</span><span class="token punctuation">(</span><span class="token number"><span class="hljs-number">1001</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"username or password error"</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>  
<span class="token punctuation">}</span>  
  
<span class="token comment"><span class="hljs-comment"><span class="markdown">/** 

* 刷新token
*/
("/refreshToken")
public AuthResult refreshToken( String refreshToken) {
String username = (String)redisTemplate.opsForHash().get(refreshToken, "username");
if(StringUtil.isEmpty(username)){
return new AuthResult(1003, "refreshToken error");
}

    <span class="token comment"><span class="hljs-comment">//生成新的token  </span></span>
    <span class="hljs-built_in">String</span> newToken <span class="token operator">=</span> JWTUtil<span class="token punctuation">.</span><span class="token function">generateToken</span><span class="token punctuation">(</span>username<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    redisTemplate<span class="token punctuation">.</span><span class="token function">opsForHash</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">put</span><span class="token punctuation">(</span>refreshToken<span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"token"</span></span><span class="token punctuation">,</span> newToken<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token keyword"><span class="hljs-keyword">return</span></span> <span class="token keyword"><span class="hljs-keyword">new</span></span> <span class="token class-name">AuthResult</span><span class="token punctuation">(</span><span class="token number"><span class="hljs-number">0</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"success"</span></span><span class="token punctuation">,</span> newToken<span class="token punctuation">,</span> refreshToken<span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  

<span class="token metadata symbol"><span class="hljs-meta">@GetMapping</span></span><span class="token punctuation">(</span><span class="token string"><span class="hljs-string">"/"</span></span><span class="token punctuation">)</span>  
public <span class="hljs-built_in">String</span> <span class="token function">index</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>  
    <span class="token keyword"><span class="hljs-keyword">return</span></span> <span class="token string"><span class="hljs-string">"auth-service: "</span></span> <span class="token operator">+</span> LocalDateTime<span class="token punctuation">.</span><span class="token function">now</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">format</span><span class="token punctuation">(</span>DateTimeFormatter<span class="token punctuation">.</span><span class="token function">ofPattern</span><span class="token punctuation">(</span><span class="token string"><span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span></span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  

}

4、application配置信息

Java代码

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、启动类

Java代码

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

改造SpringCloud Gateway工程

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

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

Java代码

@Component  
public class JWTAuthFilter implements GlobalFilter, Ordered{  
    @Override  
    public int getOrder() {  
        return -100;  
    }  
<span class="token annotation punctuation"><span class="hljs-meta">@Override</span></span>  
<span class="token keyword"><span class="hljs-function"><span class="hljs-keyword">public</span></span></span><span class="hljs-function"> </span><span class="token class-name"><span class="hljs-function">Mono</span></span><span class="token generics"><span class="token punctuation"><span class="hljs-function">&lt;</span></span><span class="token class-name"><span class="hljs-function">Void</span></span><span class="token punctuation"><span class="hljs-function">&gt;</span></span></span><span class="hljs-function"> </span><span class="token function"><span class="hljs-function"><span class="hljs-title">filter</span></span></span><span class="token punctuation"><span class="hljs-function"><span class="hljs-params">(</span></span></span><span class="token class-name"><span class="hljs-function"><span class="hljs-params">ServerWebExchange</span></span></span><span class="hljs-function"><span class="hljs-params"> exchange</span></span><span class="token punctuation"><span class="hljs-function"><span class="hljs-params">,</span></span></span><span class="hljs-function"><span class="hljs-params"> </span></span><span class="token class-name"><span class="hljs-function"><span class="hljs-params">GatewayFilterChain</span></span></span><span class="hljs-function"><span class="hljs-params"> chain</span></span><span class="token punctuation"><span class="hljs-function"><span class="hljs-params">)</span></span></span><span class="hljs-function"> </span><span class="token punctuation">{</span>  
    <span class="token class-name">String</span> url <span class="token operator">=</span> exchange<span class="token punctuation">.</span><span class="token function">getRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getURI</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getPath</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
      
    <span class="token comment"><span class="hljs-comment">//忽略以下url请求  </span></span>
    <span class="token keyword"><span class="hljs-keyword">if</span></span><span class="token punctuation">(</span>url<span class="token punctuation">.</span><span class="token function">indexOf</span><span class="token punctuation">(</span><span class="token string"><span class="hljs-string">"/auth-service/"</span></span><span class="token punctuation">)</span> <span class="token operator">&gt;=</span> <span class="token number"><span class="hljs-number">0</span></span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
        <span class="token keyword"><span class="hljs-keyword">return</span></span> chain<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>exchange<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>  
      
    <span class="token comment"><span class="hljs-comment">//从请求头中取得token  </span></span>
    <span class="token class-name">String</span> token <span class="token operator">=</span> exchange<span class="token punctuation">.</span><span class="token function">getRequest</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getHeaders</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getFirst</span><span class="token punctuation">(</span><span class="token string"><span class="hljs-string">"Authorization"</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token keyword"><span class="hljs-keyword">if</span></span><span class="token punctuation">(</span><span class="token class-name">StringUtil</span><span class="token punctuation">.</span><span class="token function">isEmpty</span><span class="token punctuation">(</span>token<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>  
        <span class="token class-name">ServerHttpResponse</span> response <span class="token operator">=</span> exchange<span class="token punctuation">.</span><span class="token function">getResponse</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        response<span class="token punctuation">.</span><span class="token function">setStatusCode</span><span class="token punctuation">(</span><span class="token class-name">HttpStatus</span><span class="token punctuation">.</span>OK<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        response<span class="token punctuation">.</span><span class="token function">getHeaders</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token string"><span class="hljs-string">"Content-Type"</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"application/json;charset=UTF-8"</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
          
        <span class="token class-name">Response</span> res <span class="token operator">=</span> <span class="token keyword"><span class="hljs-keyword">new</span></span> <span class="token class-name">Response</span><span class="token punctuation">(</span><span class="token number"><span class="hljs-number">401</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"401 unauthorized"</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword"><span class="hljs-keyword">byte</span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> responseByte <span class="token operator">=</span> <span class="token class-name">JSONObject</span><span class="token punctuation">.</span><span class="token function">fromObject</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token class-name">StandardCharsets</span><span class="token punctuation">.</span>UTF_8<span class="token punctuation">)</span><span class="token punctuation">;</span>  
          
        <span class="token class-name">DataBuffer</span> buffer <span class="token operator">=</span> response<span class="token punctuation">.</span><span class="token function">bufferFactory</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">wrap</span><span class="token punctuation">(</span>responseByte<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword"><span class="hljs-keyword">return</span></span> response<span class="token punctuation">.</span><span class="token function">writeWith</span><span class="token punctuation">(</span><span class="token class-name">Flux</span><span class="token punctuation">.</span><span class="token function">just</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>  
      
    <span class="token comment"><span class="hljs-comment">//请求中的token是否在redis中存在  </span></span>
    <span class="token keyword"><span class="hljs-keyword">boolean</span></span> verifyResult <span class="token operator">=</span> <span class="token class-name">JWTUtil</span><span class="token punctuation">.</span><span class="token function">verify</span><span class="token punctuation">(</span>token<span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token keyword"><span class="hljs-keyword">if</span></span><span class="token punctuation">(</span><span class="token operator">!</span>verifyResult<span class="token punctuation">)</span><span class="token punctuation">{</span>  
        <span class="token class-name">ServerHttpResponse</span> response <span class="token operator">=</span> exchange<span class="token punctuation">.</span><span class="token function">getResponse</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        response<span class="token punctuation">.</span><span class="token function">setStatusCode</span><span class="token punctuation">(</span><span class="token class-name">HttpStatus</span><span class="token punctuation">.</span>OK<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        response<span class="token punctuation">.</span><span class="token function">getHeaders</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token string"><span class="hljs-string">"Content-Type"</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"application/json;charset=UTF-8"</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>  

        <span class="token class-name">Response</span> res <span class="token operator">=</span> <span class="token keyword"><span class="hljs-keyword">new</span></span> <span class="token class-name">Response</span><span class="token punctuation">(</span><span class="token number"><span class="hljs-number">1004</span></span><span class="token punctuation">,</span> <span class="token string"><span class="hljs-string">"invalid token"</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword"><span class="hljs-keyword">byte</span></span><span class="token punctuation">[</span><span class="token punctuation">]</span> responseByte <span class="token operator">=</span> <span class="token class-name">JSONObject</span><span class="token punctuation">.</span><span class="token function">fromObject</span><span class="token punctuation">(</span>res<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getBytes</span><span class="token punctuation">(</span><span class="token class-name">StandardCharsets</span><span class="token punctuation">.</span>UTF_8<span class="token punctuation">)</span><span class="token punctuation">;</span>  
          
        <span class="token class-name">DataBuffer</span> buffer <span class="token operator">=</span> response<span class="token punctuation">.</span><span class="token function">bufferFactory</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">wrap</span><span class="token punctuation">(</span>responseByte<span class="token punctuation">)</span><span class="token punctuation">;</span>  
        <span class="token keyword"><span class="hljs-keyword">return</span></span> response<span class="token punctuation">.</span><span class="token function">writeWith</span><span class="token punctuation">(</span><span class="token class-name">Flux</span><span class="token punctuation">.</span><span class="token function">just</span><span class="token punctuation">(</span>buffer<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
    <span class="token punctuation">}</span>  
      
    <span class="token keyword"><span class="hljs-keyword">return</span></span> chain<span class="token punctuation">.</span><span class="token function">filter</span><span class="token punctuation">(</span>exchange<span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token punctuation">}</span>  

}

3、关键的application配置信息

Java代码

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  

最后针对上面的高频常问面试题我还总结出了适合于1-5年以上开发经验的java程序员面试涉及到的绝大部分面试题答案做成了文档学习笔记文件以及架构视频资料免费分享给大家(包括Dubbo、Redis、Netty、zookeeper、Spring cloud、分布式、高并发等架构技术资料),希望能帮助到您面试前的复习且找到一个好的工作,也节省大家在网上搜索资料的时间来学习,也可以关注我一下以后会有更多干货分享。免费获取方式:加入Java进阶之路:878249276

原文地址:https://www.jianshu.com/p/cf9ad8c3621d
posted @ 2019-11-26 14:58  星朝  阅读(751)  评论(0编辑  收藏  举报