当前位置:网站首页>API gateway / API gateway (IV) - use of Kong - Integrated JWT and fuse plug-in
API gateway / API gateway (IV) - use of Kong - Integrated JWT and fuse plug-in
2022-04-23 14:19:00 【anron】
One 、 Preface
Use Kong Medium JWT The plug-in needs to be in Kong Of Consumers Create a Consumer, Then in the Consumer Of Credentials Set in JWT Of key and secret.
Assume that 3 A scenario in which a single sign on module is used by a project team , Use Kong Gateway to JWT Token To intercept .
- A The project team is responsible for single sign on
/api/user Provide login , Login interface
- B The project team is responsible for APP1
/api/app1 application 1
/api/common/app1 Query page without login
- C The project team is responsible for APP2
/api/app2 application 2
/api/common/app2 Query page without login
Kong The gateway is wrong /api/user,/api/common Conduct JWT Token Intercept , Only right /api/app1,/api/app2 Conduct JWT Token Intercept
Call when the user logs in /api/user/login The interface verifies the user name and password , After verification, the system will userid and mobile Write to JWT Token in , And with it Token by KEY Put in redis in .
After the client logs in, put JWT Token Put in HTTP Header in , request /api/app1 perhaps /api/app2 Application interface for , If JWT Token Invalid or expired , stay Kong The gateway is blocked , Will not call to the back end /api/app1 or /api/app2 Application interface for .
app1 or app2 After receiving the request , Read first HTTP Header Medium Authorization value ( namely :Bearer + 1 A space +Token), Then read... In this project redis, If no data is found, call A Remote interface of project team ( Each project team has its own DB, Do not have access to other projects DB, It can only be accessed through the remote interface ), For security reasons ,B and C Project group has no key , Be able to Token To analyze , Only A The project team can start from Token Resolve in UserID and Mobile.
Kong No such function was found in the gateway : Auto parse Token Medium UserID and Mobile, Add to Header Then call the back-end application , There is no need to analyze later . although Request Transformer plug-in unit Sure remove/rename/replace/add/append Corresponding body/headers/querstring.
Two 、 Create user
2.1 add to Consumer
Click on Consumers Medium Create Consumer Button , Then input username,username=AllUsers, Or just a name , Just create one .
All users share one Consumer, There are both advantages and disadvantages .
advantage : No need to synchronize Kong Medium Consumer And user data in your own database
shortcoming : Plug ins such as current limiting can only be used according to IP, Can't press Consumer Limit .
2.2 establish Key and Secret
Credentials->JWT->Create JWT ,algorithm=HS256, Others are empty by default
3、 ... and 、 add to JWT plug-in unit
Set up claims to verify = exp, Otherwise, it will expire token Can request ,nbf No need to set
exp: Definition jwt The expiration time of
nbf: Definition jwt The effective time of
Set up exp after , If token When it expires, you will be prompted "token expired".
Four 、Java engineering
Some modules under single sign on project , Mainly JWT Token The award of
4.1 modify POM file
stay pom.xml Add... To the file jwt
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.3.0</version>
</dependency>
4.2 JwtUtil class
JWT_KEY、JWT_SECRET To work with Kong Medium Customer The settings inside are the same
package com.anron.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.algorithms.Algorithm;
import java.util.Date;
/**
* @Author: Anron
* @Date: 2020/4/13 14:07
*/
public class JwtUtil {
private static final String JWT_KEY = "9vQeIbdszK6Pq6Lcf0y8khnQ6yr5779P";
private static final String JWT_SECRET = "sZuEfoA9Vkwm8mhkM6Nr97eDX2YGdSu5";
/**
* 7 Days overdue
*/
public static final long JWT_EXPIRATION = (long) 7 * 24 * 60 * 60000;
/**
* Test environment 30 Minutes expired
*/
public static final long JWT_EXPIRATION_TEST = (long) 30 * 60000;
/**
* iat Date of issue withIssuedAt
* nbf entry-into-force time withNotBefore
* exp Expiration time withExpiresAt
* sub The theme
* iss Issued by people
* aud The receiving party
*/
public static String createJwtToken(Integer userId, String userNameOrMobile, long ttlMillis) {
String token = null;
try {
token = JWT.create()
.withIssuer(JwtUtil.JWT_KEY)
.withIssuedAt(new Date())
.withNotBefore(new Date())
.withClaim("userid", userId)
.withClaim("username", userNameOrMobile)
.withClaim("sub", "anron company")
.withExpiresAt(new Date(System.currentTimeMillis() + ttlMillis))
.sign(Algorithm.HMAC256(JwtUtil.JWT_SECRET));
} catch (JWTCreationException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return token;
}
public static DecodedJWT decryptToken(final String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JwtUtil.JWT_SECRET))
.withIssuer(JwtUtil.JWT_KEY)
.build();
jwt = verifier.verify(token);
} catch (TokenExpiredException e) {
e.printStackTrace();
} catch (JWTDecodeException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return jwt;
}
}
4.3 Test class
package com.anron;
import com.anron.util.JwtUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class AnronApplicationTests {
@Test
void contextLoads() {
Integer userId = 1001;
String userName = "admin";
String token = JwtUtil.createJwtToken(userId, userName, JwtUtil.JWT_EXPIRATION);
System.out.println(token);
}
@Test
void test1() {
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhbnJvbiBjb21wYW55IiwibmJmIjoxNTkwMTI3MTY3LCJpc3MiOiI5dlFlSWJkc3pLNlBxNkxjZjB5OGtoblE2eXI1Nzc5UCIsImV4cCI6MTU5MDczMTk2NywiaWF0IjoxNTkwMTI3MTY3LCJ1c2VyaWQiOjEwMDEsInVzZXJuYW1lIjoiYWRtaW4ifQ.AeoDSUZRPsoQAUfkJUTZJuU5e-CI5SEmihrHlw39Cuc";
DecodedJWT jwt = JwtUtil.decryptToken(token);
if (jwt != null) {
System.out.println("userid = " + jwt.getClaim("userid").asInt());
System.out.println("username = " + jwt.getClaim("username").asString());
System.out.println("sub = " + jwt.getClaim("sub").asString());
System.out.println(" The issuance of time = " + jwt.getClaim("iat").asDate());
System.out.println(" entry-into-force time = " + jwt.getClaim("nbf").asDate());
System.out.println(" Expiration time = " + jwt.getClaim("exp").asDate());
}
}
}
5、 ... and 、 Fuse plug in
stay Kong Add... To the list Request Termination plug-in unit , Configure with default
版权声明
本文为[anron]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231409381109.html
边栏推荐
- Thread group ThreadGroup uses introduction + custom thread factory class to implement threadfactory interface
- Introduction to loan market quotation interest rate (LPR) and loan benchmark interest rate
- 微信小程序客服接入,实现发送和接收消息
- 修改Firebase Emulators的默认侦听IP
- Uni app message push
- uni-app消息推送
- 微信小程序将原生请求通过es6的promise来进行优化
- 金融行业云迁移实践 平安金融云整合HyperMotion云迁移解决方案,为金融行业客户提供迁移服务
- JumpServer
- js 键值判断
猜你喜欢
关于云容灾,你需要知道这些
x509证书cer格式转pem格式
回顾2021:如何帮助客户扫清上云最后一公里的障碍?
正则表达式
容灾有疑问?点这里
MySQL数据库讲解(八)
MYSQL一种分表实现方案及InnoDB、MyISAM、MRG_MYISAM等各种引擎应用场景介绍
After entering the new company, the operation and maintenance engineer can understand the deployment of the system from the following items
微信小程序将原生请求通过es6的promise来进行优化
什么是云迁移?云迁移的四种模式分别是?
随机推荐
MySQL数据库讲解(十)
进入新公司,运维工程师从下面这几项了解系统的部署
JS parabola motion packaging method
云迁移的六大场景
OpenStack如何跨版本升级
Date的after时间判断
ansible及常用模块的使用
SED 学以致用
yml引用其他变量
TLS/SSL 协议详解 (30) SSL中的RSA、DHE、ECDHE、ECDH流程与区别
json date时间日期格式化
Gif to still image processing
mysql 5.1升级到5.611
Recyclerview advanced use (II) - simple implementation of vertical drag and drop sorting
SSH 通过跳板机连接远程主机
线程组ThreadGroup使用介绍+自定义线程工厂类实现ThreadFactory接口
mysql 5.1升级到5.66
金融行业云迁移实践 平安金融云整合HyperMotion云迁移解决方案,为金融行业客户提供迁移服务
操作系统常见面试题目:
微信小程序客服接入,实现发送和接收消息