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 implement Cross-domain Authentication by Java JWT

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

Today, I would like to share with you the relevant knowledge about how to achieve cross-domain authentication in Java JWT. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.

1. Introduction to JWT

JWT (JSON Web Token) is a popular cross-domain authentication solution and an open standard (RFC 7519). It defines a compact, self-contained way to securely transfer information between parties as JSON objects. This information can be verified and trusted because it is digitally signed.

2. The structure of JWT

JWT is made up of three paragraphs of information: head (header), payload (payload) and signature (visa). Concatenated together to form a JWT string.

For example:

EyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.

EyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.

SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

You can see the data by decoding the above Token using the online verification tool (https://jwt.io/)), as shown in the following figure

2.1 head (header)

The header of JWT carries two pieces of information:

(1) declaration type: here is mainly JWT.

(2) declare the encryption algorithm: usually use HMAC SHA256 directly.

For example:

{"alg": "HS256", "typ": "JWT"}

The alg attribute indicates the algorithm used for the signature

The default algorithm for JWT signature is HMAC SHA256

The alg attribute value HS256 is the HMAC SHA256 algorithm.

The type attribute represents the token type, in this case JWT.

2.2 load (payload)

The load is not only the main body of the JWT, but also a JSON object. The load consists of three parts:

(1) Registered Claims in the standard: a set of predefined declarations that are not mandatory but are recommended.

Iss (issuer): JWT issuer

Sub (subject): the user for which JWT is directed

Aud (audience): the party that receives the JWT

Exp (expiration): the expiration time of the JWT must be greater than the issuance time.

Nbf (not before): defines when the JWT is not available before.

Iat (issued at): the release time of JWT, UNIX timestamp.

Jti (JWT ID): the unique ID number of the JWT.

(2) Public statement: you can add any information, generally add user-related information or other necessary information needed by the business, but it is not recommended to add sensitive information.

(3) Private statements: statements jointly defined by providers and consumers are generally not recommended to store sensitive information.

2.3 Visa (signature)

The third part of JWT is a visa information, which consists of three parts: header (after base64), payload (after base64), and secret (key, which needs to be saved).

For example:

HMACSHA256 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret)

The signature is used to verify that the message has not been changed during redelivery, and for a Token signed with a private key, it can also verify that the sender of the JWT is what it calls the sender.

Secret is stored on the server, and the signing and generation of JWT is also on the server. Secret is used for JWT signing and verification, so secret is the private key of the server and should not be exposed in any scenario.

3. The principles of JWT

The principle of JWT is that after the server is authenticated, a JSON object is generated and sent back to the user, as shown below.

{"sub": "1234567890", "name": "Helen", "admin": true}

Then, when the user communicates with the server, the client sends back the JSON object in the request. The server relies only on this JSON object to identify the user. To prevent users from tampering with data, the server adds a signature when the object is generated.

The server does not save any session data, that is, the server becomes stateless, making it easier to extend.

4. The usage of JWT

The client receives the JWT returned by the server and stores it in Cookie or localStorage.

After that, the client will carry JWT in its interaction with the server. If it is stored in Cookie, it can be sent automatically, but not across domains, so it is typically placed in the Header Authorization field of the HTTP request. When cross-domain, JWT can also be placed in the data body of the POST request.

5. Problems and trends of JWT

JWT can be used not only for authentication, but also for information exchange. Making good use of JWT can help reduce the number of times the server requests a database.

The produced token can contain basic information, such as id, user nicknames, avatars, etc., to avoid checking the database again.

It is stored on the client side and does not occupy the memory resources of the server.

JWT is not encrypted by default, but it can be encrypted. After the original token is generated, it can be encrypted again.

When JWT is not encrypted, some private data cannot be transmitted over JWT.

The biggest disadvantage of JWT is that the server does not save session state, so it is not possible to cancel tokens or change token permissions during use. In other words, once the JWT is issued, it will remain valid during the validity period.

JWT itself contains authentication information, and token is encoded by base64, so it can be decoded, so objects before token encryption should not contain sensitive information. Once the information is leaked, anyone can get all permissions of the token. In order to reduce embezzlement, the validity period of JWT should not be set too long. For some important operations, users should authenticate every time they use them.

To reduce embezzlement and theft, JWT does not recommend using the HTTP protocol to transmit the code, but using the encrypted HTTPS protocol for transmission.

6. Integrate JWT token 6.1 add jwt tools to the module rely on io.jsonwebtoken jjwt 6.2 to create JWT tool classes / * JWT tool classes * / public class JwtHelper {/ / Expiration time private static long tokenExpiration = 24,60,60,1000; / / token signature key private static String tokenSignKey = "123456" / / generate token public static String createToken (Long userId) based on parameters String userName) {String token = Jwts.builder () .setSubject ("YYGH-USER") / / sets the expiration time for 30 minutes. SetExpiration (new Date (System.currentTimeMillis () + tokenExpiration)) / / sets the topic information user id and user name .claim ("userId") UserId) .claim ("userName", userName) / / signature hash .signWith (SignatureAlgorithm.HS512, tokenSignKey) .signsWith (CompressionCodecs.GZIP) .compact () Return token;} / / get the user id public static Long getUserId (String token) {if (StringUtils.isEmpty (token)) return null; Jws claimsJws = Jwts.parser (). SetSigningKey (tokenSignKey) .parseClaimsJws (token) from the token string; Claims claims = claimsJws.getBody (); Integer userId = (Integer) claims.get ("userId"); return userId.longValue () } / / get the user name public static String getUserName (String token) {if (StringUtils.isEmpty (token)) return "; Jws claimsJws = Jwts.parser (). SetSigningKey (tokenSignKey) .parseClaimsJws (token); Claims claims = claimsJws.getBody (); return (String) claims.get (" userName ");}}

Write a main function to test:

Public static void main (String [] args) {String token = JwtHelper.createToken (1L, "lucy"); System.out.println (token); System.out.println (JwtHelper.getUserId (token)); System.out.println (JwtHelper.getUserName (token));}

There is no problem with signing and parsing.

These are all the contents of the article "how Java JWT implements cross-domain authentication". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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