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 Jwt login authentication with code

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

Share

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

How to use the code to achieve Jwt login authentication, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Based on nimbus-jose-jwt encapsulated a jwt, and only need to customize the HandlerInterceptor implementation class and WebMvcConfigurer implementation class to introduce the use of jwt login authentication in the project.

Starter in Spring Boot is a very important mechanism, which can abandon the previous complicated configuration and integrate it into starter. The application only needs to introduce starter dependency into Maven, and Spring Boot can automatically scan the information to be loaded and start the corresponding default configuration. Starter frees us from the processing of various dependent libraries and the need to configure all kinds of information. Spring Boot automatically discovers the required Bean through the class under the classpath path and registers it into the IOC container. Spring Boot provides spring-boot-starter dependency modules for daily enterprise application research and development scenarios. All of these dependency modules follow the conventional default configuration and allow us to adjust these configurations, that is, to follow the concept of "convention is greater than configuration".

Next, we will customize a starter based on the previously encapsulated ron-jwt. As long as the project introduces this starter in the dependency, and then defines a simple configuration, you can use the login authentication of jwt.

Create a new project and configure dependency

The starter provided by Spring Boot is named as spring-boot-starter-xxx. It is officially recommended that custom starter use the xxx-spring-boot-starter naming convention to distinguish the starter provided by the Spring Boot ecosystem. So we built a new project, ron-jwt-spring-boot-starter.

Introducing dependencies into pom.xml

Org.springframework.boot spring-boot-configuration-processor true org.springframework.boot spring-boot-autoconfigure org.springframework.boot spring-boot-starter-web io.ron ron-jwt 1.0-SNAPSHOT

The main function of spring-boot-configuration-processor is to generate the spring-configuration-metadata.json file under META-INF at compile time, which is mainly used by IDE, that is, you can enter the class where the configuration properties are located through ctrl + click in the application.properties file.

The main function of spring-boot-autoconfigure is to provide automatic assembly function.

Spring-boot-starter-web is because we will have built-in HandlerInterceptor implementation classes and WebMvcConfigurer implementation classes.

Ron-jwt is the jwt library that we packaged in the previous article.

Define configuration item management classes

We define JwtProperties to declare which configuration items are available to consumers of starter.

@ ConfigurationProperties (prefix = "ron.jwt") public class JwtProperties {private String tokenName = JwtUtils.DEFAULT_TOKEN_NAME; private String hmacKey; private String jksFileName; private String jksPassword; private String certPassword; / / issuer private String issuer; / / subject private String subject; / / audience private String audience; private long notBeforeIn; private long notBeforeAt; private long expiredIn; private long expiredAt;}

The @ ConfigurationProperties annotation specifies that all configuration items are prefixed with ron.jwt.

The basic use of @ ConfigurationProperties is simple: we provide a class with fields for each external property to be captured. Please note the following points:

The prefix defines which external properties will be bound to the fields of the class.

According to Spring Boot's loose binding rules, the property name of the class must match the name of the external property.

We can simply initialize a field with a value to define a default value.

The class itself can be package private.

The fields of the class must have public setter methods.

> Spring Boot loose binding rules (relaxed binding): > > Spring Boot uses some loose binding property rules. Therefore, the following variants will be bound to the tokenName attribute: > > + ron.jwt.tokenname=Authorization > + ron.jwt.tokenName=Authorization > + ron.jwt.token_name=Authorization > + ron.jwt.token-name=Authorization

Implement related functions

In the previous article, we implemented the HandlerInterceptor implementation class and the WebMvcConfigurer implementation class in a specific business project. In fact, this part is also a common logic in the project, so we consider placing these implementations in starter. The project can not do unnecessary customization, directly through the introduction of starter can use the jwt authentication function.

JwtInterceptorpublic class JwtInterceptor implements HandlerInterceptor {private Logger logger = LoggerFactory.getLogger (JwtInterceptor.class); private static final String PREFIX_BEARER = "Bearer"; @ Autowired private JwtProperties jwtProperties; @ Autowired private JwtService jwtService; @ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / if not mapped to the method directly through if (! (handler instanceof HandlerMethod)) {return true } HandlerMethod handlerMethod = (HandlerMethod) handler; Method method = handlerMethod.getMethod (); / / check whether there is @ AuthRequired annotation. If required () is false, skip if (method.isAnnotationPresent (AuthRequired.class)) {AuthRequired authRequired = method.getAnnotation (AuthRequired.class); if (! authRequired.required ()) {return true }} String token = request.getHeader (jwtProperties.getTokenName ()); logger.info ("token: {}", token); if (StringUtils.isEmpty (token) | | token.trim () .equals (PREFIX_BEARER.trim () {return true;} token = token.replace (PREFIX_BEARER, "") / / set token JwtContext.setToken (token) in thread local variables; / / set real data passed in thread local variables, such as current user information, String payload = jwtService.verify (token); JwtContext.setPayload (payload); return onPreHandleEnd (request, response, handler, payload) } public boolean onPreHandleEnd (HttpServletRequest request, HttpServletResponse response, Object handler, String payload) throws Exception {return true } @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {/ / be sure to clean up the thread local variable JwtContext.removeAll () before the thread ends.

The onPreHandleEnd method is a default implementation that can also inherit JwtInterceptor if necessary in business, adding custom logic to this method. One possible scenario is to put the token of JWT into Redis for timeout management.

JwtInterceptorConfigpublic class JwtInterceptorConfig implements WebMvcConfigurer {private JwtInterceptor jwtInterceptor; public JwtInterceptorConfig (JwtInterceptor jwtInterceptor) {this.jwtInterceptor = jwtInterceptor;} @ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (jwtInterceptor) .addPathPatterns ("/ *");}}

All requests are intercepted by default, and in the previous article, we mentioned that you can work with @ AuthRequired to filter requests that do not need to be intercepted.

Write automatic configuration logic JwtAutoConfiguration@Configuration@EnableConfigurationProperties (JwtProperties.class) public class JwtAutoConfiguration {@ Autowired private JwtProperties jwtProperties; @ Bean public JwtConfig jwtConfig () {JwtConfig jwtConfig = new JwtConfig (); BeanUtils.copyProperties (jwtProperties, jwtConfig); return jwtConfig;} @ Bean public JwtService jwtService () {JwtConfig jwtConfig = jwtConfig (); return JwtUtils.obtainJwtService (jwtConfig) } @ Bean public JwtInterceptor jwtInterceptor () {return new JwtInterceptor ();} @ Bean public JwtInterceptorConfig jwtInterceptorConfig () {return new JwtInterceptorConfig (jwtInterceptor ());}}

The purpose of @ EnableConfigurationProperties is to introduce a class that uses the @ ConfigurationProperties annotation and make it effective.

The @ EnableConfigurationProperties document explains: when the @ EnableConfigurationProperties annotation is applied to your @ Configuration, any beans annotated by @ ConfigurationProperties will be automatically configured by the Environment attribute. This style of configuration is particularly suitable for use with SpringApplication's external YAML configuration.

Integrate starter to make it work

There are two ways to make starter work in an application.

Load via SPI mechanism-take effect passively

Load our starter through Spring Boot's SPI mechanism.

Create a new WEB-INF/spring.factories file in the resources directory.

The META-INF/spring.factories file is the core file that the Spring Boot framework recognizes and parses starter. The spring.factories file is a Spring container that helps Bean other than the Spring Boot project package (that is, add the Bean in the dependency to the pom file) to register with the Spring Boot project. Since the @ ComponentScan annotation can only scan the Bean within the Spring Boot project package and register it with the Spring container, you need the @ EnableAutoConfiguration annotation to register the Bean outside the project package. The spring.factories file, on the other hand, is used to record the Bean class names that need to be registered outside the project package.

Introduction of org.springframework.boot.autoconfigure.EnableAutoConfiguration=io.ron.jwt.starter.JwtAutoConfiguration custom Enable annotations-take effect actively

We need to proactively declare that the starter is enabled when the starter component is integrated into our Spring Boot application. We customize a @ Enable annotation and then introduce the automatic configuration class through the Import annotation.

@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Import ({JwtAutoConfiguration.class}) @ Documented@Inheritedpublic @ interface EnableJwt {}

If the active method is used, the META-INF/spring.factories file that implements the passive effect needs to be removed.

Package and publish starter

Use mvn install to package and install locally

You can publish to a remote repository using mvn deploy.

Test the application

Modify the dependency in pom.xml to introduce ron-jwt-spring-boot-starter.

Io.ron ron-jwt-spring-boot-starter 1.0-SNAPSHOT

Remove the HandlerInterceptor implementation class and the WebMvcConfigurer implementation class.

Configure the value of ron.jwt.hmac-key in application.yml to provide the JWT signature and verification capabilities implemented by the HMAC algorithm.

If starter takes a passive approach, you can run the program now, and then use Postman to test and observe the results.

If starter takes a proactive approach, you need to add the @ EnableJwt annotation to the project startup class to introduce jwt-starter.

@ SpringBootApplicationpublic class JwtStarterApplication {public static void main (String [] args) {SpringApplication.run (JwtStarterApplication.class, args);}} is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

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