In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains the "JTW how to achieve authentication and authorization", the article explains the content 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 "JTW how to achieve authentication and authorization" bar!
Partial summary of JWT theory
Is an open standard based on json that is implemented to deliver declarations in a network application environment. It is especially suitable for single sign-on scenarios of distributed sites. The declaration of jwt is generally used to transfer authenticated user identity information between the identity provider and the service provider in order to obtain resources from the server and to add some additional life information used by other business logic.
Composition
JWT consists of three parts, as shown below:
Header: header
Alg represents the algorithm for generating signatures. Typ represents the type of token (type), and JWT tokens are written as JWT.
{"alg": "HS256", "typ": "JWT"}
Payload: payload
Optional parameter: iss: issuer sub: facing user aud: receiver iat (issued at): issue time exp (expires): expiration time nbf (not before): cannot be received processing time, before this cannot be received processing jti:JWT ID provides a unique identity for web token
{"sub": "123456", "exp": "1564641412"}
Signature: signature
Signatures generated with header and payload prevent header and payload from being tampered with. You need to specify a password (secret). The password is only saved on the server and cannot be exposed to the user, and a matching password (secret) is required to parse successfully.
String signature = HMACSHA512 (base64UrlEncode (header) + "." + base64UrlEncode (payload), secret); JWT practice pom file introduces related dependencies io.jsonwebtoken jjwt 0.9.0 configuration interceptor
You need to block all interfaces except login and open static paths
@ Configurationpublic class WebConfig extends WebMvcConfigurationSupport {@ Autowired private JwtInterceptor jwtInterceptor; / * configure static resources * @ param registry * / @ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {registry.addResourceHandler ("/ * *") .addResourceLocations ("classpath:/static/") Registry.addResourceHandler ("/ swagger-ui.html") .addResourceLocations ("classpath:/META-INF/resources/"); registry.addResourceHandler ("/ webjars/**") .addResourceLocations ("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers (registry) } / * Register interceptor * @ param registry * / @ Override public void addInterceptors (InterceptorRegistry registry) {/ / add intercepted request And exclude several unintercepted requests registry.addInterceptor (jwtInterceptor) .addPathPatterns ("/ * *") .origindePathPatterns ("/ loginController/loginSystem", "/ swagger-ui.html", "/ static/**", "/ swagger-resources/**", "/ webjars/**", ") } add configuration request interceptor @ Componentpublic class JwtInterceptor extends HandlerInterceptorAdapter {@ Autowired private JwtTokenConfig jwtTokenConfig; @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {String header = Constant.getContentProperties () .getStringProperty ("header"); / / get request token String reqToken = getJwt (request); if (jwtTokenConfig.validateJwtToken (reqToken)) {return true;} return false } / * get and return token information * @ param request * @ return * / private String getJwt (HttpServletRequest request) {/ / get String authHeader = request.getHeader ("Authorization") from header; String header = Constant.getContentProperties () .getStringProperty ("header") If (StringUtils.startsWith (authHeader, header)) {authHeader = authHeader.replace (header+ "", ");} return authHeader;} add JWT configuration class
The configuration class is used to generate, parse, and verify Token. Due to business requirements, a new token will be dispatched when it expires.
@ Configurationpublic class JwtTokenConfig {private static final Logger logger = LoggerFactory.getLogger (JwtTokenConfig.class); @ Autowired private JwtTokenMapper jwtTokenMapper; / / read configuration file information private String expire = Constant.getContentProperties () .getStringProperty ("expire"); private String secret = Constant.getContentProperties () .getStringProperty ("secret"); private String header = Constant.getContentProperties () .getStringProperty ("header") / * generate token * @ param subject * @ return * / public String generateToken (String subject) {/ / set expiration time Date expireDate = new Date (System.currentTimeMillis () + 1000 * Long.parseLong (expire)); / / build header Map headMap = new HashMap (); headMap.put ("alg", SignatureAlgorithm.HS256.getValue ()) HeadMap.put ("typ", "JWT"); / / Custom component Map claims = new HashMap (); claims.put ("created", DateUtil.formatDate (new Date (), DateUtil.YEAR_TO_SECOND)) String access_token = Jwts.builder () .setHeader (headMap) .signWith (SignatureAlgorithm.HS512) Secret) .setClaims (claims) / / for users .setSubject (subject) / / Expiration time .setExpiration (expireDate) / / generate token .compact () / / refresh the token information in the database refreshToken (subject, access_token, expireDate); logger.info (subject+ "generated token:" + access_token); return access_token;} / * * obtain signature information * @ param token * @ return * / public Claims getClaimsFromToken (String token) {Claims claims = null Try {claims = Jwts.parser () .setSigningKey (secret) .parseClaimsJws (token) .getBody (); logger.info ("parsing token result:" + claims) } catch (ExpiredJwtException e) {/ / token expired to create and return a new token logger.info ("token expired, creating a new token\ n"); JwtToken jwtToken = jwtTokenMapper.selectByToken (token); if (jwtToken! = null) {String newToken = generateToken (jwtToken.getUserCode ()) Claims = Jwts.parser () .setSigningKey (secret) .parseClaimsJws (newToken) .getBody (); logger.info ("parsing token result:" + claims ");} else {logger.info (" invalid token ") }} catch (Exception e) {logger.info ("parsing exception");} return claims } / * token check * @ param token * @ return * / public boolean validateJwtToken (String token) {if (StringUtils.isNotBlank (token)) {/ / get the signature information in token and verify the expiration time Claims claims = getClaimsFromToken (token); JwtToken jwtToken = jwtTokenMapper.selectByUserCode (claims.getSubject ()) HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes ()) .getResponse (); if (jwtToken = = null | | jwtToken.getJwtId ()
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.