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

时间:2021-08-04 06:15:56

写在前面

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

Java架构笔记:用JWT对SpringCloud进行认证和鉴权
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代码

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

* 登录认证

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

        <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

*/

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

}

    <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

Java架构笔记:用JWT对SpringCloud进行认证和鉴权的更多相关文章

  1. springcloud zuul shiro网关鉴权并向服务传递用户信息

    1.pom文件 <dependencies> <!--eureka客户端--> <dependency> <groupId>org.springfram ...

  2. 【Spring Cloud &amp&semi; Alibaba 实战 &vert; 总结篇】Spring Cloud Gateway &plus; Spring Security OAuth2 &plus; JWT 实现微服务统一认证授权和鉴权

    一. 前言 hi,大家好~ 好久没更文了,期间主要致力于项目的功能升级和问题修复中,经过一年时间的打磨,[有来]终于迎来v2.0版本,相较于v1.x版本主要完善了OAuth2认证授权.鉴权的逻辑,结合 ...

  3. 认证鉴权与API权限控制在微服务架构中的设计与实现(四)

    引言: 本文系<认证鉴权与API权限控制在微服务架构中的设计与实现>系列的完结篇,前面三篇已经将认证鉴权与API权限控制的流程和主要细节讲解完.本文比较长,对这个系列进行收尾,主要内容包括 ...

  4. Java架构师之路 Spring学习笔记&lpar;一&rpar; Spring介绍

    前言 这是一篇原创的Spring学习笔记.主要记录我学习Spring4.0的过程.本人有四年的Java Web开发经验,最近在面试中遇到面试官总会问一些简单但我不会的Java问题,让我觉得有必要重新审 ...

  5. Java架构师-十项全能学习笔记(1)

    Java架构师-十项全能学习笔记(1) @Configuration @EnableStateMachine public class OrderStateMachineConfig extends ...

  6. 【转载】Java学习笔记

    转载:博主主页 博主的其他笔记汇总 : 学习数据结构与算法,学习笔记会持续更新: <恋上数据结构与算法> 学习Java虚拟机,学习笔记会持续更新: <Java虚拟机> 学习Ja ...

  7. 最新咕咆&plus;鲁班&plus;图灵&plus;享学&plus;蚂蚁&plus;硅谷&plus;源码 Java架构师资料《Java架构师VIP课程》

    最新的Java架构师完整资料,完整视频+源码+文档. 每一套都是一百多个G的资料,无密. JAVA架构师全套课程 咕泡学院互联网架构师第一期 咕泡学院互联网架构师第二期 咕泡学院互联网架构师第三期 博 ...

  8. 阿里巴巴内部Java成长笔记,首次曝光!真的香!

    前言 关于技术人如何成长的问题,一直以来都备受关注,因为程序员职业发展很快,即使是相同起点的人,经过几年的工作或学习,会迅速拉开极大的差距,所以技术人保持学习,提升自己,才能够扛得住不断上赶的后浪,也 ...

  9. 0032 Java学习笔记-类加载机制-初步

    JVM虚拟机 Java虚拟机有自己完善的硬件架构(处理器.堆栈.寄存器等)和指令系统 Java虚拟机是一种能运行Java bytecode的虚拟机 JVM并非专属于Java语言,只要生成的编译文件能匹 ...

随机推荐

  1. 视频演示eworkflow集成定制aspx页面的过程

    eworkflow自定义工作流系统,集成eform自定义表单,可以做到在线编辑流程,在线编辑表单.eform也提供在线建立业务表,维护表字段等,所以通过eworkflow+eform可以在线完成业务流 ...

  2. hiho48 &colon; 欧拉路&&num;183&semi;一

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho最近在玩一个解密类的游戏,他们需要控制角色在一片原始丛林里面探险,收集道具,并找到最后的宝藏.现在他们控制的 ...

  3. Broadwell I7-5775c&sol;5675c BSOD 蓝屏问题

    今年6月末Intel发布了第五代台式机CPU,代号Broadwell,跳票一年多,仅有两款零售型号,I7-5775C和I5-5675C. 第一时间就买来试用,当时还是在日亚购买的,等待了10天左右终于 ...

  4. ssh 命令

    常用的ssh命令 cd 切换目录 1.查看日志:举例: tail -f tomcat/apache-tomcat-6.0.26/logs/catalina.2010-11-10.out 2.pwd   ...

  5. html部分---a标签的用法、放置图片与表格;

    a标签的用法: 1.加链接  herf <a href="http://www.baidu.com">百度一下</a> 2.加载本地文件 <a hre ...

  6. window live writer的曲折安装过程

           之前一直使用windows live writer2012写日志,由于之前重装了系统,所以需要重新安装writer,本以为是一个很简单的过程,你就是安装个软件吗.... 然而事实是... ...

  7. 使用Xcode查找项目中的中文字符串

    打开”Find Navigator” 切换搜索模式到 “Find > Regular Expression” 输入@"[^"]*[\u4E00-\u9FA5]+[^&quot ...

  8. Linux多线程——使用互斥量同步线程

    前文再续,书接上一回,在上一篇文章: Linux多线程——使用信号量同步线程中,我们留下了一个如何使用互斥量来进行线程同步的问题,本文将会给出互斥量的详细解说,并用一个互斥量解决上一篇文章中,要使用两 ...

  9. &lbrack;置顶&rsqb; ruby变量详解&lpar;收集&plus;整理&rpar;

    ruby的变量有局部变量,全局变量,实例变量,类变量,常量. 1.局部变量 局部变量以一个小写字母开头或下划线开头 局部变量有局部作用域限制(比如一个block内),它的作用域起始于声明处,结束于该声 ...

  10. RTMP直播应用与延时分析

    直播应用中,RTMP和HLS基本上可以覆盖所有客户端观看,HLS主要是延时比较大,RTMP主要优势在于延时低. 一.应用场景 低延时应用场景包括:  .  互动式直播:譬如2013年大行其道的美女主播 ...