前后端分离方案token工具类

JWT

  1. 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准,可实现无状态、分布式的Web应用授权。
  2. 另外还有一种轻量级的方案(减轻网络压力)随机数token方案(在redis中做映射,该值与userid做成字典),这种方式也可达到无状态分布式服务器的情况

关于jwt–官网:https://jwt.io/

基于token的鉴权机制类似于http协议也是无状态的,它不需要在服务端去保留用户的认证信息或者会话信息。这就意味着基于token认证机制的应用不需要去考虑用户在哪一台服务器登录了,这就为应用的扩展提供了便利。
流程上是这样的:
1、用户使用用户名密码来请求服务器 2、
2、服务器进行验证用户的信息 服务器通过验证发送给用户一个token
3、 客户端存储token,并在每次请求时附送上这个token值 服务端验证token值,并返回数据
4、这个token必须要在每次请求时传递给服务端,它应该保存在请求头里,
另外,服务端要支持CORS(跨来源资源共享)策略,一般我们在服务端这么做就可以了Access-Control-Allow-Origin:*。


jwt后端的工具类(加密解密)

<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
   <dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>2.2.0</version>
   </dependency>

工具类编写

import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author riversky E-mail:riversky@126.com
 * @version 创建时间 : 2018/1/22.
 */
public class JwtUtils {
    /**
     * 密钥
     */
    private static  final String SECRET="xxxx";
    /**
     * 默认字段key:exp
     */
    private static final String EXP="exp";
    /**
     * 默认字段key:payload
     */
    private static final String PAYLOAD="payload";

    /**
     * 加密
     * @param object 加密数据
     * @param maxTime 有效期(毫秒数)
     * @param <T>
     * @return
     */
    public static <T> String encode(T object,long maxTime){
        try{
            final JWTSigner signer=new JWTSigner(SECRET);
            final Map<String ,Object> data=new HashMap<>(10);
            ObjectMapper objectMapper=new ObjectMapper();
            String jsonString=objectMapper.writeValueAsString(object);
            data.put(PAYLOAD,jsonString);
            data.put(EXP,System.currentTimeMillis()+maxTime);
            return signer.sign(data);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 数据解密
     * @param jwt 解密数据
     * @param tClass 解密类型
     * @param <T>
     * @return
     */
    public static <T> T decode(String jwt,Class<T> tClass){
        final JWTVerifier jwtVerifier=new JWTVerifier(SECRET);
        try{
            final Map<String,Object> data=jwtVerifier.verify(jwt);
            //判断数据是否超时或者符合标准
            if(data.containsKey(EXP)&&data.containsKey(PAYLOAD)){
                long exp= (long) data.get(EXP);
                long currentTimeMillis=System.currentTimeMillis();
                if(exp>currentTimeMillis){
                    String json= (String) data.get(PAYLOAD);
                    ObjectMapper objectMapper=new ObjectMapper();
                    return objectMapper.readValue(json,tClass);
                }
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    public static class  User{
        Integer id;
        String name;
        String password;
        public User() {
        }
        public User(Integer id, String name, String password) {
            this.id = id;
            this.name = name;
            this.password = password;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
//        有效期10秒
//        加密:
        String token=encode(new User(1,"张三","riversky"),10000);
        System.out.println(token);
//      解密
        User user=decode(token,User.class);
        System.out.println(user);
    }
}

使用方式

一般在验证验证中将该字段作为token发送到头信息中。客户端只起到转发的功能(如果只有web应用可以考虑放到cookie中,这样就可以避免每次客户端手动的添加头信息)

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值