服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - SpringBoot+Vue+JWT的前后端分离登录认证详细步骤

SpringBoot+Vue+JWT的前后端分离登录认证详细步骤

2022-01-17 12:24全栈阿文 Java教程

这篇文章主要介绍了SpringBoot+Vue+JWT的前后端分离登录认证,其实创建后端springboot工程也很简单,本文安装idea步骤一步步给大家详细介绍,需要的朋友可以参考下

前后端分离的概念在现在很火,最近也学习了一下前后端分离的登录认证。

创建后端springboot工程

这个很简单了,按照idea的一步一步创建就行
文件目录结构:

SpringBoot+Vue+JWT的前后端分离登录认证详细步骤

pom文件依赖导入。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<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三个字段

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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);
    }
}

不要忘了前后端分离中的跨域问题, 我们在后端进行跨域问题的解决。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@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页面:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<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页面

?
1
2
3
4
5
6
7
8
9
10
11
12
export default {
  data(){
    return {
      admin: ''
    }
  },
  created() {
    //admin的信息从保存在客户端中的信息中获取
    this.admin = JSON.parse(window.localStorage.getItem('access-admin'))
  }
}
</script>

index.js路由

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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+Vue+JWT的前后端分离登录认证的文章就介绍到这了,更多相关SpringBoot登录认证内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_45462732/article/details/120435889

延伸 · 阅读

精彩推荐