您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關SpringBoot+Vue+JWT的前后端分離登錄認證的步驟是怎樣的,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
這個很簡單了,按照idea的一步一步創建就行
文件目錄結構:
pom文件依賴導入。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version> <scope>provided</scope> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.0</version> </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> <version>1.1.1</version> </dependency> </dependencies>
創建實體類:User
//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; }
創建JWToken
public class JwtToken { private static long time = 1000*5; private static String signature = "admin"; //創建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; } //校驗token,布爾類型 public static boolean checkToken(String token){ if (token ==null){ return false; } try { Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token); }catch (Exception e){ return false; } return true; } }
創建控制器UserController
@RestController public class UserController { private final String USERNAME = "admin"; private final String PASSWORD = "123123"; //login方法 @GetMapping("/login") public User login(User user){ if(USERNAME.equals(user.getUsername()) && PASSWORD.equals(user.getPassword())){ //添加token user.setToken(JwtToken.createToken()); return user; } return null; } //校驗token @GetMapping("/checkToken") //接收前端請求過來的header中的token,然后去jwtoken校驗方法里校驗這個token public Boolean checkToken(HttpServletRequest request){ String token = request.getHeader("token"); return JwtToken.checkToken(token); } }
不要忘了前后端分離中的跨域問題, 我們在后端進行跨域問題的解決。
@Configuration public class CrosConfiguration implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOriginPatterns("*") .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }
Login頁面:
<script> export default { name: "Login", data(){ return{ ruleForm: { username: 'admin', password: '123123' }, rules: { username: [{required: true, message: '請輸入用戶名', trigger: 'blur'}], password: [{required: true, message: '請輸入密碼', 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!=null){ //將token信息保存在本地客戶端 localStorage.setItem('access-admin',JSON.stringify(response.data)) _this.$router.replace({path:'/'}) } }) }else{ console.log('error submit!'); return false; } }) } } }; </script>
home頁面
export default { data(){ return { admin: '' } }, created() { //admin的信息從保存在客戶端中的信息中獲取 this.admin = JSON.parse(window.localStorage.getItem('access-admin')) } } </script>
index.js路由
router.beforeEach((to, from, next) => { if (to.path.startsWith('/login')) { //取出token信息 window.localStorage.removeItem('access-admin') next() } else { //獲取token的信息。 let admin = JSON.parse(window.localStorage.getItem('access-admin')) if (!admin) { next({path: '/login'}) } else { //校驗token合法性 axios({ url:'http://localhost:8080/checkToken', method:'get', headers:{ token:admin.token } }).then((response) => { console.log(response.data) if(!response.data){ console.log('校驗失敗') next({path: '/error'}) } }) next() } } }
以上就是SpringBoot+Vue+JWT的前后端分離登錄認證的步驟是怎樣的,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。