In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What this article shares to you is about the steps of the front and back end separation login authentication of SpringBoot+Vue+JWT. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
Create a backend springboot project
This is very simple, just follow the steps of idea to create it.
File directory structure:
The pom file depends on import.
Org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.projectlombok lombok 1.16.16 provided io.jsonwebtoken jjwt 0. 9.1 javax.xml.bind jaxb-api 2.3.0 com.sun.xml.bind jaxb-impl 2.3.0 com.sun.xml.bind jaxb-core 2.3.0 Javax.activation activation 1.1.1
Create an entity class: User
/ / three fields of username,password,token
Private String username; private String password; private String token; public String getUsername () {return username;} public void setUsername (String username) {this.username = username;} public String getPassword () {return password;} public void setPassword (String password) {this.password = password;} public String getToken () {return token } public void setToken (String token) {this.token = token;}
Create JWToken
Public class JwtToken {private static long time = 1000005; private static String signature = "admin"; / / the method to create token public static String createToken () {JwtBuilder jwtBuilder = Jwts.builder () String jwtToken = jwtBuilder / / header .setHeaderParam ("typ", "JWT") .setHeaderParam ("alg", "HS256") / / payload .claim ("username", "tom") .claim ("role") "admin") .setSubject ("admin-test") .setExpiration (new Date (System.currentTimeMillis () + time)) .setId (UUID.randomUUID () .toString ()) / / signature .signWith (SignatureAlgorithm.HS256,signature) .compact () Return jwtToken;} / / check token, Boolean type public static boolean checkToken (String token) {if (token = = null) {return false;} try {Jws claimsJws = Jwts.parser (). SetSigningKey (signature) .parseClaimsJws (token);} catch (Exception e) {return false;} return true;}}
Create a controller UserController
@ RestControllerpublic class UserController {private final String USERNAME = "admin"; private final String PASSWORD = "123123"; / / login method @ GetMapping ("/ login") public User login (User user) {if (USERNAME.equals (user.getUsername ()) & & PASSWORD.equals (user.getPassword () {/ / add token user.setToken (JwtToken.createToken ()); return user } return null;} / / verify token @ GetMapping ("/ checkToken") / / receive the token in the header requested by the front end, and then verify the token public Boolean checkToken (HttpServletRequest request) {String token = request.getHeader ("token"); return JwtToken.checkToken (token);}} in the jwtoken verification method.
Don't forget the cross-domain problem in the front-end separation, we solve the cross-domain problem in the back-end.
@ Configurationpublic class CrosConfiguration implements WebMvcConfigurer {@ Override public void addCorsMappings (CorsRegistry registry) {registry.addMapping ("/ * *") .allowedOrigin patterns ("*"). AllowedMethods ("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials (true) .maxAge (3600) .allowedHeaders ("*") }} create a Vue project at the front end
Login page:
Export default {name: "Login", data () {return {ruleForm: {username: 'admin', password:' 123123'}, rules: {username: [{required: true, message: 'please enter a user name' Trigger: 'blur'}], password: [{required: true, message:' please enter your password', trigger: 'blur'}]} Methods: {handleSubmit () {this.$refs.ruleForm.validate ((valid) = > {if (valid) {let _ this = this axios.get ('http://localhost:8080/login',) {params:_this.ruleForm}) .then (function (response) {if (response. data contains null) {/ / save the token information on the local client localStorage.setItem ('access-admin' JSON.stringify (response.data)) _ this.$router.replace ({path:'/'})})} else {console.log ('error submittance') Return false;})}}
Home page
Export default {data () {return {admin:''}}, the information of created () {/ / admin gets this.admin = JSON.parse (window.localStorage.getItem ('access-admin'))}} from the information stored in the client
Index.js routing
Router.beforeEach ((to, from, next) = > {if (to.path.startsWith ('/ login')) {/ / take out token information window.localStorage.removeItem ('access-admin') next ()} else {/ / get token information. Let admin = JSON.parse (window.localStorage.getItem ('access-admin')) if (! admin) {next ({path:' / login'})} else {/ / verify token validity axios ({url:' http://localhost:8080/checkToken', method:'get') Headers: {token:admin.token}}) .then ((response) = > {console.log (response.data) if (! response.data) {console.log ('verification failed') next ({path:'/ error'})}) next ()}}
These are the steps of the front and back end of SpringBoot+Vue+JWT to separate login authentication. 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.
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.