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 Json Web Token based on springSecurity

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is about how to achieve Json Web Token based on springSecurity. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.

SecurityJwt an implementation of Json Web Token based on springSecurity

GitHub address

Summary 1. SpringSecurity

Spring Security, a security framework based on Spring AOP and Servlet filters. It provides a comprehensive security solution that handles identity confirmation and authorization at both the Web request level and the method call level.

From the Spring family bucket series, seamless connection with SpringBoot. Provide declarative security access control function for application system, which reduces the work of writing a lot of repetitive code for enterprise system security control.

II. JSON Web Token

JSON Web Token (JWT) is a specification to be exact. It's actually a string that consists of three parts-- the Header, the playload, and the signature.

The header (Header) is used to describe the most basic information about the JWT, that is, the information declaration of the JWT itself, such as the algorithm used to sign.

Playload is the place where valid information is stored. The information is divided into three parts-the declaration part, the public part (subject) and the private part (claim).

Visa (signature) requires base64 encrypted header and base64 encrypted payload. Concatenate the string, and then salt the secret combination encryption through the encryption declared in header (note: secret is saved on the server side).

In the distributed system, it is easier to retrieve the saved user information directly according to token and verify the availability of token.

III. Introduction to the development environment

Java version: 1.8

Build tool: Gradle (at present, the mainstream build tool in China is still Maven, but the author does not want to use Maven after using Gradle, because Gradle is really much more convenient. Its warehouse structure is backward compatible with Maven, which means that any Maven repository can be used.

Build.gradle file:

Plugins {id 'org.springframework.boot' version' 2.2.0.RELEASE'id 'io.spring.dependency-management' version' 1.0.8.RELEASE'id 'java'} group =' org.zuoyu'version = '1.0.0'sourceCompatibility =' 1.8'configurations {compileOnly {extendsFrom annotationProcessor}} repositories {/ / Alibaba's Maven warehouse maven {url'is used here Http://maven.aliyun.com/nexus/content/groups/public/'}} dependencies {implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation' org.springframework.boot:spring-boot-starter-security' implementation 'org.springframework.boot:spring-boot-starter-web' compileOnly' org.projectlombok:lombok' runtimeOnly 'mysql:mysql-connector-java' annotationProcessor' org.projectlombok:lombok'// jwt dependency Runtime ('io.jsonwebtoken:jjwt-jackson:0.10.7') runtime (' io.jsonwebtoken:jjwt-impl:0.10.7') compile ('io.jsonwebtoken:jjwt-api:0.10.7') testImplementation (' org.springframework.boot:spring-boot-starter-test') {exclude group: 'org.junit.vintage' Module: 'junit-vintage-engine'} testImplementation' org.springframework.security:spring-security-test'} test {useJUnitPlatform ()} IV. Source code description here only analyzes the key code (where JwtConstants.java is my custom final variable class) Note: in the configuration file of security There is no need to use session to close the session manager. 1. JwtTokenUtils.java (utility class of JWT) / * build JWT * * @ param subject-entity * @ param authorities-permission * @ param expiration-retention time * @ return-token * / private static String createJwt (String subject, String authorities, long expiration) {long nowMillis = System.currentTimeMillis () Return Jwts.builder () .setId (JwtConstants.createTokenId ()) .signWith (SECRET_KEY, SignatureAlgorithm.HS256) .setIssuer (JwtConstants.JWT_ISSUER) .setSubject (subject) .claim (JwtConstants.ROLE_CLAIMS, authorities) .setIssuedAt (new Date (nowMillis)) .setNotBefore (new Date (nowMillis)) .setExpiration (new Date (nowMillis + expiration * 1000L)) .compact ();}

Here we use the Jwts.builder () method in the official dependency package to create a token, where--

SignWith is to set the private key and encryption method. SECRET_KEY is the private key and SignatureAlgorithm.HS256 is the encryption method.

SetSubject sets the public part, which can be decrypted on the client side.

Claim is the setting private part, and its parameter is in the form of key-value.

SetIssuedAt is the time when the token was issued.

SetNotBefore is the effective time of token.

SetExpiration is the failure time of token.

Parse token:

/ * parse token * * @ param token-* @ return-Claims * / private static Claims parseJwt (String token) {return Jwts.parser () .setSigningKey (SECRET_KEY) .parseClaimsJws (token) .getBody ();}

Here the focus is on setSigningKey, passing in our private key SECRET_KEY at the time of creation.

There are also several ways to interact easily with security:

/ * build token * * @ param user-account * @ return-* / public static String createToken (User user, boolean isRememberMe) {long expiration = isRememberMe? JwtConstants.EXPIRATION_REMEMBER: JwtConstants.EXPIRATION; String spacer = ","; List authorities = Arrays.stream (user.getRoles (). Split (spacer)) .map (role-> "ROLE_" + role) .map (Collectors.toList ()); return createJwt (JsonUtil.beanToJsonString (user), JsonUtil.objectToJsonString (authorities), expiration) } / * get the user * * @ param token-token * @ return-User * / public static User getUserByToken (String token) {String subject = parseJwt (token). GetSubject (); return JsonUtil.jsonStringToBean (subject, User.class) } / * obtain the user's permission * @ param token-token * @ return-permission list * / public static Collection getAuthoritiesByToken (String token) {String roles = parseJwt (token) .get (JwtConstants.ROLE_CLAIMS). ToString (); return JsonUtil.jsonStringToCollection (roles, SimpleGrantedAuthority.class);} 2. AuthenticationSuccessHandlerImpl.java (execution behavior after Security login) / * login is successfully implemented. * * @ author zuoyu * * / @ Scope (value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {@ Override public void onAuthenticationSuccess (HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {String rememberMe = request.getParameter (JwtConstants.USER_LOGIN_REMEMBER_ME); boolean isRememberMe = Boolean.parseBoolean (rememberMe); User principal = (User) authentication.getPrincipal (); String token = JwtTokenUtils.createToken (principal, isRememberMe); response.setContentType ("application/json;charset=utf-8") Response.setHeader (JwtConstants.TOKEN_HEADER, token); response.setStatus (HttpServletResponse.SC_OK); PrintWriter responseWriter = response.getWriter (); responseWriter.write ("{\" message\ ":\" login succeeded\ "); responseWriter.flush (); responseWriter.close ();}}

The main idea of this code is-after a successful login, get the authenticated user information (user) in authentication, and then convert the user to token and return it to the client. The isRememberMe is based on whether or not token is given a different valid time for true (see the complete source code).

3. JwtAuthorizationFilter.java (custom filter based on JWT authentication) / * JWT permission filter. * * @ author zuoyu * @ program jwt * @ create 2019-10-17 16:26 * * / @ Slf4jpublic class JwtAuthorizationFilter extends BasicAuthenticationFilter {public JwtAuthorizationFilter (AuthenticationManager authenticationManager) {super (authenticationManager);} @ Override protected void doFilterInternal (HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {String token = request.getHeader (JwtConstants.TOKEN_HEADER); if (StringUtils.isEmpty (token)) {chain.doFilter (request, response); return } User user = JwtTokenUtils.getUserByToken (token); Collection authorities = JwtTokenUtils.getAuthoritiesByToken (token); UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken (user, null, authorities); SecurityContextHolder.getContext (). SetAuthentication (usernamePasswordAuthenticationToken); super.doFilterInternal (request, response, chain);}}

This code fetches the token from the request and parses the user information (user) and permission information (authorities) from the token. According to the user information (user) and permission information (authorities), the privilege identity (authentication) belonging to the security framework is created and stored in the current security environment.

5. Use the account name field of automatic form creation (JPA) registration (login) after the launch of the method project (login) and the account password field of userName registration (login). The "remember me" field of passWord login is how to use rememberMe--

After logging in, there is a field Authorization in the header Headers of the response Response, which is Token.

Subsequent visits need to indicate identity by carrying the field Authorization and its value in the header Headers of the Request.

The default aging time of rememberMe is one hour, the aging time of true is 7 days, and the path is set in org.zuoyu.security.jwt.constants.JwtConstants.java.

The test path looks at the org.zuoyu.security.jwt.controller.AuthController.java class.

The above is how to implement Json Web Token based on springSecurity. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow 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

Internet Technology

Wechat

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

12
Report