Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Spring Cloud to create a unified authentication service based on JWT

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to understand Spring Cloud based on JWT to create a unified authentication service", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to understand Spring Cloud based on JWT to create a unified authentication service" it!

Table structure

The case in this tutorial omits the step of checking the database, and you can add it yourself, but the design of the table still needs to be explained to you. The form of the user table is shown in figure 1.

The related code is shown below.

Create table auth_user (id int (4) not null, accessKey varchar (100) not null, secretKey varchar (100) not null, Primary key (id)); Alter table auth_user comment 'authenticated user Information Table'

Here are only a few simple fields, if you have other needs, you can expand on your own. The accessKey and secretKey in the code are identities for the user.

JWT tool class encapsulation

The GitHub address of JWT is: https://github.com/jwtk/jjwt, and the dependency configuration code is shown below.

Io.jsonwebtokenjjwt0.7.0

There are several main methods to authenticate with tool classes:

Generate Token.

Check to see if Token is legal.

Refresh the RSA public and private keys.

Token is generated after user authentication, a Token is generated through the user's ID. The Token is encrypted by RSA encryption, and the content of the Token includes the user's ID and expiration time.

Checking Token is to check whether it is a legitimate user according to the Token brought by the caller, that is, to decrypt the Token, which can be decrypted and indicate that it is valid within the validity period, and return the user ID if it is legal.

The function of refreshing RSA public key and private key is to prevent the disclosure of public key and private key. Public key and private key are usually written to death, but we can configure them. After the configuration management center is integrated, the public key and private key can be dynamically modified, and the object information of the public key and private key needs to be re-initialized after modification.

The code to get the Token is shown below.

/ * * obtain Token** @ param uid user ID* @ param exp expiration time in minutes * @ return*/public static String getToken (String uid, int exp) {Long endTime = System.currentTimeMillis () + 1000 * 60 * exp;return Jwts.builder () .setSubject (uid) .setExpiration (new Date (endTime)) .signWith (SignatureAlgorithm.RS512, priKey) .compact ();}

The code to check whether Token is legal is shown below.

/ * check whether Token is legal * * @ param token* @ return JWTResult*/public JWTResult checkToken (String token) {try {Claims claims = Jwts.parser (). SetSigningKey (pubKey) .parseClaimsJws (token). GetBody (); String sub = claims.get ("sub", String.class); return new JWTResult (true, sub, "legitimate request", ResponseCode.SUCCESS_CODE.getCode ()) } catch (ExpiredJwtException e) {/ / when parsing the JWT string, if the 'expiration time field' is earlier than the current time, / / an ExpiredJwtException exception will be thrown, indicating that the request has expired return new JWTResult (false, null, "token expired", ResponseCode.TOKEN_TIMEOUT_CODE.getCode ()) } catch (SignatureException e) {/ / when parsing a JWT string, if the key is incorrect, the parsing will fail, and a / / SignatureException exception is thrown, indicating that the JWT string is a forged return new JWTResult (false, null, "illegal request", ResponseCode.NO_AUTH_CODE.getCode ());} catch (Exception e) {return new JWTResult (false, null, "illegal request", ResponseCode.NO_AUTH_CODE.getCode ());}}

The complete code is shown below.

/ * API calls the authentication tool class, using RSA encryption * / public class JWTUtils {private static RSAPrivateKey priKey;private static RSAPublicKey pubKey;private static class SingletonHolder {private static final JWTUtils INSTANCE = new JWTUtils ();} public synchronized static JWTUtils getInstance (String modulus, String privateExponent, String publicExponent) {if (priKey = = null & & pubKey = = null) {priKey = RSAUtils.getPrivateKey (modulus, privateExponent); pubKey = RSAUtils.getPublicKey (modulus, publicExponent);} return SingletonHolder.INSTANCE } public synchronized static void reload (String modulus, String privateExponent, String publicExponent) {priKey = RSAUtils.getPrivateKey (modulus, privateExponent); pubKey = RSAUtils.getPublicKey (modulus, publicExponent);} public synchronized static JWTUtils getInstance () {if (priKey = = null & & pubKey = = null) {priKey = RSAUtils.getPrivateKey (RSAUtils.modulus, RSAUtils.private_exponent); pubKey = RSAUtils.getPublicKey (RSAUtils.modulus, RSAUtils.public_exponent);} return SingletonHolder.INSTANCE } / * * obtain Token * * @ param uid user ID * @ param exp expiration time (in minutes) * @ return * / public static String getToken (String uid, int exp) {long endTime = System.currentTimeMillis () + 1000 * 60 * exp;return Jwts.builder (). SetSubject (uid) .setExpiration (new Date (endTime)) .signWith (SignatureAlgorithm.RS512, priKey) .compact () } / * get Token * * @ param uid user ID * @ return * / public String getToken (String uid) {long endTime = System.currentTimeMillis () + 1000 * 60 * 1440 setSubject Jwts.builder (). SetSubject (uid) .setExpiration (new Date (endTime)) .signWith (SignatureAlgorithm.RS512, priKey) .signWith () } / * check whether Token is legal * * @ param token * @ return JWTResult * / public JWTResult checkToken (String token) {try {Claims claims = Jwts.parser (). SetSigningKey (pubKey) .parseClaimsJws (token). GetBody (); String sub = claims.get ("sub", String.class); return new JWTResult (true, sub, "legitimate request", ResponseCode.SUCCESS_CODE.getCode ()) } catch (ExpiredJwtException e) {/ / when parsing the JWT string, if the "expiration time field" is already earlier than the current time, an ExpiredJwtException exception will be thrown, indicating that the request has expired return new JWTResult (false, null, "token expired", ResponseCode.TOKEN_TIMEOUT_CODE.getCode ()) } catch (SignatureException e) {/ / when parsing a JWT string, if the key is incorrect, the parsing will fail and a SignatureException exception is thrown, indicating that the JWT string is a forged return new JWTResult (false, null, "illegal request", ResponseCode.NO_AUTH_CODE.getCode ());} catch (Exception e) {return new JWTResult (false, null, "illegal request", ResponseCode.NO_AUTH_CODE.getCode ()) }} public static class JWTResult {private boolean status;private String uid;private String msg;private int code;public JWTResult () {super ();} public JWTResult (boolean status, String uid, String msg, int code) {super (); this.status = status;this.uid = uid;this.msg = msg;this.code = code;} public int getCode () {return code;} public void setCode (int code) {this.code = code } public String getMsg () {return msg;} public void setMsg (String msg) {this.msg = msg;} public boolean isStatus () {return status;} public void setStatus (boolean status) {this.status = status;} public String getUid () {return uid;} public void setUid (String uid) {this.uid = uid;} Authentication API

When the authentication API is used by the caller to authenticate, an encrypted Token is returned to the caller when the authentication is passed, and the other party can use this Token to request other services. The authentication acquisition Token code is shown below.

@ PostMapping ("/ token") public ResponseData auth (@ RequestBody AuthQuery query) throws Exception {if (StringUtils.isBlank (query.getAccessKey ()) | | StringUtils.isBlank (query.getSecretKey () {return ResponseData.failByParam ("accessKey and secretKey not null");} User user = authService.auth (query); if (user = = null) {return ResponseData.failByParam ("Certification failure");} JWTUtils jwt = JWTUtils.getInstance () Return ResponseData.ok (jwt.getToken (user.getId (). ToString ());}

The authentication parameter code is shown below.

/ * * API user authentication parameter class * / public class AuthQuery {private String accessKey;private String secretKey;// get set...}

The auth method in AuthService determines whether there is such a user based on accessKey and secretKey.

Thank you for your reading, the above is the content of "how to understand Spring Cloud to create a unified authentication service based on JWT". After the study of this article, I believe you have a deeper understanding of how to understand Spring Cloud to create a unified authentication service based on JWT. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report