In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the method of Gateway authentication in SpringCloud". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. JWT implements micro-service authentication
JWT is generally used to implement single sign-on. Single sign-on: for example, there are many games under Tencent, including lol, Flying car, etc., log in once on QQ Game's war platform, and then these different platforms can be logged in directly. This is the use scenario of single sign-on. JWT is a technology to achieve single sign-on, and others include oath3 and so on.
1 what is micro-service authentication
We have built a gateway before, and it is more suitable to use the gateway for permission verification in the gateway system.
Then we can use JWT to achieve authentication verification.
two。 Code implementation
Train of thought analysis
1. When the user enters the gateway and starts to log in, the gateway filter determines. If the user is logged in, the user will be routed to the backend management micro-service to log in.
two。 The user logs in successfully, and the backend management microservice issues JWT TOKEN information back to the user.
3. The user enters the gateway again to start access, and the gateway filter receives the TOKEN carried by the user.
4. The gateway filter parses the TOKEN to determine whether it has permission. If so, it is released. If not, an unauthenticated error is returned.
Issue token
(1) create a class: JwtUtil
Package com.mye.nacosprovider.jwt; import com.alibaba.fastjson.JSON;import io.jsonwebtoken.Claims;import io.jsonwebtoken.JwtBuilder;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;import org.springframework.stereotype.Component; import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.util.Base64;import java.util.Date;import java.util.*;@Componentpublic class JwtUtil {/ / the key for encryption and decryption is used to generate key public static final String JWT_KEY = "IT1995" / * generate encrypted key secretKey * @ return * / public static SecretKey generalKey () {byte [] encodedKey = Base64.getDecoder () .decode (JwtUtil.JWT_KEY); SecretKey key = new SecretKeySpec (encodedKey, 0, encodedKey.length, "AES"); return key;} public static String createJWT (String id, String subject, long ttlMillis) {SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256 / / specify the signature algorithm used when signing, that is, the part of header, which has been encapsulated by jjwt. Long nowMillis = System.currentTimeMillis (); / / the time when the JWT was generated Date now = new Date (nowMillis); SecretKey key = generalKey (); / / the key secret used when generating the signature. This method is locally encapsulated and can generally be read from the local configuration file. Keep in mind that this secret key cannot be exposed. It is the private key of your server and should not be revealed in any scenario. Once the client knows about the secret, it means that the client can sign the jwt itself. JwtBuilder builder = Jwts.builder () / / this is actually new a JwtBuilder. Set jwt's body// .setClaims (claims) / / if you have a private declaration, be sure to set this self-created private declaration first. This is an assignment to builder's claim, once written after the standard declaration assignment. Is to override the standard declared .setId (id) / / set jti (JWT ID): is the unique identity of the JWT, according to business needs, this can be set to a non-repetitive value, mainly used as an one-time token, thus avoiding replay attacks. .setIssuedAt (now) / / iat: the issuance time of the jwt .setSubject (subject) / / sub (Subject): represents the body of the JWT, that is, its owner, this is a string in json format, can store what userid,roldid and so on, as the only symbol of what user. .signWith (signatureAlgorithm, key); / / set signature algorithm and signature key if (ttlMillis > = 0) {long expMillis = nowMillis + ttlMillis; Date exp = new Date (expMillis); builder.setExpiration (exp); / / set expiration time} return builder.compact () / / start compressing the jwt} public static Claims parseJWT (String jwt) {SecretKey key = generalKey () such as xxxxxxxxxxxxxx.xxxxxxxxxxxxxxx.xxxxxxxxxxxxx; / / the signature key is exactly the same as the generated signature key Claims claims = Jwts.parser () / / get DefaultJwtParser .setSigningKey (key) / / set the signature key .parseClaimsJws (jwt). GetBody () / / set jwt return claims;} public static void main (String [] args) {Map user = new HashMap (); user.put ("username", "it1995"); user.put ("password", "123456"); String jwt = createJWT (UUID.randomUUID (). ToString (), JSON.toJSONString (user), 3600 * 24); System.out.println ("after encryption:" + jwt) / / decrypt Claims claims = parseJWT (jwt); System.out.println ("after decryption:" + claims.getSubject ());}}
(2) modify the login method. If the user logs in successfully, the TOKEN will be issued.
@ PostMapping ("/ login") public String login (@ RequestBody User user) {/ / look up the password String password = redisTemplate.opsForValue () .get (user.getUsername ()); System.out.println (password); boolean checkResult = BCrypt.checkpw (user.getPassword (), password); if (checkResult) {Map info = new HashMap () Info.put ("username", user.getUsername ()); String token = JwtUtil.createJWT (UUID.randomUUID (). ToString (), user.getUsername (), 3600L*1000); info.put ("token", token); return JSONUtil.toJsonStr (info);} else {return "login failed";}}
(3) testing
Gateway filter verifies token
(1) Gateway module adds dependencies
Io.jsonwebtoken jjwt 0.9.0
(2) create JWTUtil class
Package com.mye.nacosprovider.jwt; import com.alibaba.fastjson.JSON;import io.jsonwebtoken.Claims;import io.jsonwebtoken.JwtBuilder;import io.jsonwebtoken.Jwts;import io.jsonwebtoken.SignatureAlgorithm;import org.springframework.stereotype.Component; import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.util.Base64;import java.util.Date;import java.util.*;@Componentpublic class JwtUtil {/ / the key for encryption and decryption is used to generate key public static final String JWT_KEY = "IT1995" / * generate encrypted key secretKey * @ return * / public static SecretKey generalKey () {byte [] encodedKey = Base64.getDecoder () .decode (JwtUtil.JWT_KEY); SecretKey key = new SecretKeySpec (encodedKey, 0, encodedKey.length, "AES"); return key;} public static String createJWT (String id, String subject, long ttlMillis) {SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256 / / specify the signature algorithm used when signing, that is, the part of header, which has been encapsulated by jjwt. Long nowMillis = System.currentTimeMillis (); / / the time when the JWT was generated Date now = new Date (nowMillis); SecretKey key = generalKey (); / / the key secret used when generating the signature. This method is locally encapsulated and can generally be read from the local configuration file. Keep in mind that this secret key cannot be exposed. It is the private key of your server and should not be revealed in any scenario. Once the client knows about the secret, it means that the client can sign the jwt itself. JwtBuilder builder = Jwts.builder () / / this is actually new a JwtBuilder. Set jwt's body// .setClaims (claims) / / if you have a private declaration, be sure to set this self-created private declaration first. This is an assignment to builder's claim, once written after the standard declaration assignment. Is to override the standard declared .setId (id) / / set jti (JWT ID): is the unique identity of the JWT, according to business needs, this can be set to a non-repetitive value, mainly used as an one-time token, thus avoiding replay attacks. .setIssuedAt (now) / / iat: the issuance time of the jwt .setSubject (subject) / / sub (Subject): represents the body of the JWT, that is, its owner, this is a string in json format, can store what userid,roldid and so on, as the only symbol of what user. .signWith (signatureAlgorithm, key); / / set signature algorithm and signature key if (ttlMillis > = 0) {long expMillis = nowMillis + ttlMillis; Date exp = new Date (expMillis); builder.setExpiration (exp); / / set expiration time} return builder.compact () / / start compressing the jwt} public static Claims parseJWT (String jwt) {SecretKey key = generalKey () such as xxxxxxxxxxxxxx.xxxxxxxxxxxxxxx.xxxxxxxxxxxxx; / / the signature key is exactly the same as the generated signature key Claims claims = Jwts.parser () / / get DefaultJwtParser .setSigningKey (key) / / set the signature key .parseClaimsJws (jwt). GetBody () / / set jwt return claims;} public static void main (String [] args) {Map user = new HashMap (); user.put ("username", "it1995"); user.put ("password", "123456"); String jwt = createJWT (UUID.randomUUID (). ToString (), JSON.toJSONString (user), 3600 * 24); System.out.println ("after encryption:" + jwt) / / decrypt Claims claims = parseJWT (jwt); System.out.println ("after decryption:" + claims.getSubject ());}}
(3) create a filter for token authentication
/ * Authentication filter verifies token * / @ Componentpublic class AuthorizeFilter implements GlobalFilter, Ordered {private static final String AUTHORIZE_TOKEN = "token"; @ Override public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {/ / 1. Get request ServerHttpRequest request = exchange.getRequest (); / / 2. Then get the response ServerHttpResponse response = exchange.getResponse (); / / 3. If it is a login request, release if (request.getURI (). GetPath (). Contains ("/ admin/login")) {return chain.filter (exchange);} / / 4. Get the request header HttpHeaders headers = request.getHeaders (); / / 5. Get the token String token = headers.getFirst (AUTHORIZE_TOKEN) in the request header; / / 6. Determine whether there is a token in the request header if (StringUtils.isEmpty (token)) {/ / 7. Do you want to put the returned status in the response? you do not have permission to access response.setStatusCode (HttpStatus.UNAUTHORIZED); / / 8. Return return response.setComplete ();} / 9. Parse the token try {JwtUtil.parseJWT (token);} catch (Exception e) {e.printStackTrace (); / / 10 if there is a token in the request header. An error occurred in parsing jwt tokens, indicating that illegal situations such as token expiration or forgery have occurred response.setStatusCode (HttpStatus.UNAUTHORIZED); / / 11. Return return response.setComplete ();} / / 12. Release return chain.filter (exchange);} @ Override public int getOrder () {return 0;}}
(4) Test:
First, do a login test
Conducting an authentication test.
This is the end of the content of "what is the method of Gateway authentication in SpringCloud". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.