首页 > 其他分享 >JWT自学

JWT自学

时间:2022-11-08 08:57:40浏览次数:38  
标签:map jwt JWT token zsbb import 自学 com

一:导入配置文件

<!--        JWT-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>

 

二:可以先在ApplicationTests中测试看一些效果

package com.zsbb.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zsbb.jwt.Service.UserService;
import com.zsbb.jwt.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Calendar;
import java.util.HashMap;

@SpringBootTest
class JwtApplicationTests {

    @Test
    void contextLoads() {
        HashMap<String,Object> map=new HashMap<>();

        //日历类
        Calendar instance=Calendar.getInstance();
        //二十秒后过期
        instance.add(Calendar.SECOND,2000);

       String token=JWT.create()
                .withHeader(map)
//               可以放多个参数
                .withClaim("id",12)
                .withClaim("username","老王")
                .withExpiresAt(instance.getTime()) //令牌过期时间
//                密钥:zsbb
                .sign(Algorithm.HMAC256("zsbb")); //签名
        System.out.println(token);
    }

    @Test
    public void test(){
        //创建验证对象
        JWTVerifier jwtVerifier= JWT.require(Algorithm.HMAC256("zsbb")).build();

        //验证token
        DecodedJWT verify = jwtVerifier.verify

        ("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MTIsImV4cCI6MTY2Nzg2ODcxMSwidXNlcm5hbWUiOiLogIHnjosifQ.qBcsUHnQWJE0ljTGZ9IDFTh6c0xIv5mh0e5KgejiL5c\n");

        System.out.println(verify);
        //单个参数取
        System.out.println(verify.getClaim("username").asString());
        //多个参数取
        System.out.println(verify.getClaims().get("username").asString());
        System.out.println(verify.getClaims().get("id").asInt());

    }

 

效果图:

1:得到token

 

2:校验token

 

三:与SpringBoot集成首先封装utils

package com.zsbb.jwt.utis;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtis {
    private static  String SING="zsbb";
    /*
    * 生成token
    * */
    public static String getToken(Map<String,String> map){

        Calendar instance=Calendar.getInstance();
        //十天后过期
        instance.add(Calendar.SECOND,10);
        //创建Builder
        JWTCreator.Builder builder=JWT.create();

        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        String token= builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return  token;
    }
    /*
    * 验证token合法性
    * */
    public static DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

//    /*
//    * 获取token信息
//    * */
//    public static DecodedJWT getTokenInfo(String token){
//        DecodedJWT verify=JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
//        return  verify;
//    }
}

 

四:编写Entity、Service、Serviceimpl、Mapper、Controller

Entity

package com.zsbb.jwt.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String password;
}

Service

package com.zsbb.jwt.Service;

import com.zsbb.jwt.entity.User;

import java.util.List;

public interface UserService {
    User login(User user);
}

Serviceimpl

package com.zsbb.jwt.Service.impl;

import com.zsbb.jwt.Service.UserService;
import com.zsbb.jwt.entity.User;
import com.zsbb.jwt.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceimpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }
}

Controller

package com.zsbb.jwt.controller;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zsbb.jwt.Service.UserService;
import com.zsbb.jwt.entity.User;
import com.zsbb.jwt.utis.JWTUtis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/JWTlogin")
    public Map<String,Object> Login(@RequestBody User user){
        Map<String,Object> map=new HashMap<>();
        try {
            User userDB=userService.login(user);
            Map<String,String> payload=new HashMap<>();
            payload.put("id",String.valueOf(userDB.getId()));
            payload.put("name",userDB.getName());
            //生成JWT的令牌
            String token=JWTUtis.getToken(payload);
            map.put("state",true);
            map.put("msg","认证成功");
            //抛出token
            map.put("token",token);
        }catch (Exception e){
            map.put("state",false);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    @PostMapping("/text")
    public Map<String,Object> test(@RequestParam(required = true, defaultValue = "0") String token){
        Map<String,Object> map=new HashMap<>();
        //处理自己业务逻辑
        map.put("state",true);
        map.put("msg","请求成功!");
        return  map;
    }
}

 

五:封装异常处理,添加拦截器

异常处理

package com.zsbb.jwt.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zsbb.jwt.utis.JWTUtis;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        Map<String,Object> map=new HashMap<>();
        try {
            JWTUtis.verify(token);//验证令牌
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg","无效签名");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期!");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","token算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("state",false);//设置状态
        //将map转json
        String json=new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

拦截器

package com.zsbb.jwt.config;

import com.zsbb.jwt.interceptor.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new JWTInterceptor())
               //拦截的请求
               .addPathPatterns("/**")      //所有的接口都要token验证
               //放行请求
               .excludePathPatterns("/login/JWTlogin"); //所以用户的登录操作都放行
    }
}

 

六:效果图

 

校验token:

 

 

完结撒花!!!

标签:map,jwt,JWT,token,zsbb,import,自学,com
From: https://www.cnblogs.com/zsbb/p/16868470.html

相关文章

  • ctfshow JWT总结
    一、基础知识:介绍:JSONWebToken(JWT)是用来进行跨域身份验证的一种方案。构成:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoidXNlciIsImlhdCI6MTY2NzgxMDA1MX0.bsJ......
  • JWT安全性剖析
    JWT基础概念详解简介JWT(JSONWebToken)是目前最流行的跨域认证解决方案,是一种基于Token的认证授权机制。从JWT的全称可以看出,JWT本身也是Token,一种规范化之后......
  • 自学Java的学习步骤与基本态度
     一般来说,刚开始学Java,需要掌握的基础并没有那么多,但是却需要牢牢掌握。如:Java数据类型、String基本类型封装类、MySQL等基础知识,属于必备技能,不论你是什么目的学习Java,此......
  • 使用jwt,redis,实现登录
    jwt是无状态的,不需要服务端存储登录用户信息,一次性生成token后,除非过期,不然是都可以用的。但是这样就产生了token续期、用户注销等问题。token续期怎么解决呢?1、使用......
  • 自学HTML做手机网页.
    <!DOCTYPEhtml><htmllang="en"><head>  <metacharset="UTF-8">  <metahttp-equiv="X-UA-Compatible"content="IE=edge">  <metaname="viewport"c......
  • DRF访问控制(RBAC)、JWT认证
    目录RBACRBAC什么是RBACRBAC是基于角色的访问控制(Role-BasedAccessControl)在RBAC中,权限与角色相关联,用户通过成为适当角色的成员而得到这些角色的权限。这就极......
  • 关于jwt(token)储存在哪的方案
    第一种方案:(安全系数高的项目推荐这种)直接由服务端设置cookie到浏览器(客户端。jwttoken是储存在cookie的,请求是自动发送到服务器的,服务器直接获取就行,拿到验证且需要设置......
  • go-gin集成jwt认证
    今天趁热打铁,把cookie/session/jwt集成go-gin框架的认证方式,一鼓作气全code一遍,lifeisshort,showyouthecode.示例目录结构:项目入口:packagemainimport( "gin......
  • 学习笔记-JWT 安全
    JWT安全免责声明本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.关于JWT认证的基本知识点可见笔记认证&......
  • jwt的ASP.NET MVC 身份验证
    jwt的ASP.NETMVC身份验证 JsonWebToken(jwt)        一种不错的身份验证及授权方案,与Session相反,Jwt将用户信息存放在Token的payload字段......