SpringBoot+Vue+JWT的前后端分离登录认证详细步骤
前后端分离的概念在现在很火,最近也学习了一下前后端分离的登录认证。
创建后端springboot工程
这个很简单了,按照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("*"); } }
前端创建Vue项目
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的前后端分离登录认证的文章就介绍到这了,更多相关SpringBoot登录认证内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!
【文章原创作者:http://www.yidunidc.com/st.html转发请说明出处】