JWT用户登录验证

JWT用户登录验证

jwt知识介绍

登陆页面

<template>
    <div class="login-container">
        <el-form :model="ruleForm2" :rules="rules2"
                 status-icon
                 ref="ruleForm2"
                 label-position="left"
                 label-width="0px"
                 class="demo-ruleForm login-page">
            <h3 class="title">系统登录</h3>
            <el-form-item prop="username">
                <el-input type="text"
                          v-model="ruleForm2.username"
                          auto-complete="off"
                          placeholder="用户名"
                ></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password"
                          v-model="ruleForm2.password"
                          auto-complete="off"
                          placeholder="密码"
                ></el-input>
            </el-form-item>
            <el-checkbox
                    v-model="checked"
                    class="remember-me"
            >记住密码</el-checkbox>
            <el-form-item style="width:100%;">
                <el-button type="primary" style="width:100%;" @click="handleSubmit" :loading="logining">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                logining: false,
                ruleForm2: {
                    username: '',
                    password: '',
                },
                rules2: {
                    username: [{required: true, message: 'please enter your account', trigger: 'blur'}],
                    password: [{required: true, message: 'enter your password', trigger: 'blur'}]
                },
                checked: false
            }
        },
        methods: {
            handleSubmit(){
                this.$refs.ruleForm2.validate((valid) => {
                    if (valid){
                        let _this = this
                        axios.get("http://localhost:8181/user/login",{params:_this.ruleForm2}).then(function (response) {
                            console.log(response.data)
                            if (response.data != ""){
                                localStorage.setItem('access-admin',JSON.stringify(response.data))
                                _this.$router.push('/')
                            }else{
                                alert("用户名或密码错误!")
                            }

                        })
                    }

                    // if(valid){
                    //     this.logining = true;
                    //     if(this.ruleForm2.username === 'admin' &&
                    //         this.ruleForm2.password === '123456'){
                    //         this.logining = false;
                    //         sessionStorage.setItem('user', this.ruleForm2.username);
                    //         this.$router.push({path: '/'});
                    //     }else{
                    //         this.logining = false;
                    //         this.$alert('username or password wrong!', 'info', {
                    //             confirmButtonText: 'ok'
                    //         })
                    //     }
                    // }else{
                    //     console.log('error submit!');
                    //     return false;
                    // }
                })
            }
        }
    };
</script>

<style scoped>
    .login-container {
        width: 100%;
        height: 100%;
    }
    .login-page {
        -webkit-border-radius: 5px;
        border-radius: 5px;
        margin: 180px auto;
        width: 350px;
        padding: 35px 35px 15px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
    }
    .remember-me {
        margin: 0px 0px 15px;
        text-align: left;
    }
</style>

登陆过期跳转登录页面

//所有认证的跳转
router.beforeEach((to, from, next) => {
    if(to.path.startsWith('/login')){
        window.localStorage.removeItem('access-admin')
        next()
    }else{
        let admin = JSON.parse(window.localStorage.getItem('access-admin'))
        if(!admin){ //
            next({path:'/login'})
        }else{
            //校验token合法性
            axios({
                url:'http://localhost:8181/user/checkToken',
                method:'get',
                headers:{
                    token:admin.token
                }
            }).then((response) => {
                if(!response.data){
                    next({path:'/error'})
                }
            })
            next()
        }
    }
})

后端控制层

package com.vuetest.demo.controller;

import com.vuetest.demo.entity.User;
import com.vuetest.demo.util.JwtUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@CrossOrigin
public class userHandler {

    private final String USERNAME = "admin";
    private final String PASSWORD = "123";

    @GetMapping("/login")
    public User login(User user){
        if(USERNAME.equals(user.getUsername()) && PASSWORD.equals(user.getPassword())){
            user.setToken(JwtUtil.creatToken());
            return user;
        }
        return null;
    }

    @GetMapping("/checkToken")
    public Boolean checkToken(HttpServletRequest request){
         String token = request.getHeader("token");
         return  JwtUtil.checkToken(token);
    }
}

后端工具类

package com.vuetest.demo.util;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    private static long time = 1000*60*60*24;  //有效时间 :24小时
    private static String signature = "admin";

    public static String creatToken(){
         JwtBuilder builder = Jwts.builder();
         String jwtToken = builder
                 //header   标题
        .setHeaderParam("typ","JWT")
                 .setHeaderParam("alg","HS256")
                 //payload  有效载荷
        .claim("username","admin")
                 .claim("role","admin")
                 .setSubject("admin-test")
                 .setExpiration(new Date(System.currentTimeMillis()+time))
                 .setId(UUID.randomUUID().toString())
                 //signature  签名
        .signWith(SignatureAlgorithm.HS256,signature)
                 .compact();

        return jwtToken;
    }

    public static boolean checkToken(String token){
        if(token == null){
            System.out.println("1");
            return false;
        }
        try {  System.out.println("2");
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值