• spring boot整合JWT例子


    application.properties

    jwt.expire_time=3600000
    jwt.secret=MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjY34DFDSSSd =
    

    JwtUtil

    package com.osp.ucenter.jwt;
    
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Configuration;
    
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;
    
    /**
     * jwt工具类
     * 
     * @author zhangmingcheng
     */
    @Configuration
    public class JwtUtil {
    
    	private static long EXPIRATION_TIME; // 1 hour
    
    	private static String SECRET;// 秘钥
    	
    	@Value("${jwt.expire_time}")
    	public void setEXPIRATION_TIME(long eXPIRATION_TIME) {
    		EXPIRATION_TIME = eXPIRATION_TIME;
    	}
    
    	@Value("${jwt.secret}")
    	public void setSECRET(String sECRET) {
    		SECRET = sECRET;
    	}
    
    	/**
    	 * 生成jwtToken
    	 * 
    	 * @param username
    	 * @return
    	 */
    	public static String generateToken(String username) {
    		HashMap<String, Object> map = new HashMap<>();
    		// you can put any data in the map
    		map.put("username", username);
    		String jwt = Jwts.builder().setClaims(map).setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
    				.signWith(SignatureAlgorithm.HS512, SECRET).compact();
    		return jwt;
    	}
    
    	/**
    	 * 校验jwtToken
    	 * 
    	 * @param token
    	 * @return
    	 */
    	public static String validateToken(String token) {
    		if (token != null) {
    			Map<String, Object> body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
    			String username = (String) (body.get("username"));
    			if (username == null || username.isEmpty()) {
    				throw new TokenValidationException("Wrong token without username");
    			} else {
    				return username;
    			}
    		} else {
    			throw new TokenValidationException("Missing token");
    		}
    	}
    	
    	public static long getEXPIRATION_TIME(){
    		return JwtUtil.EXPIRATION_TIME;
    	}
    
    
    	static class TokenValidationException extends RuntimeException {
    		/**
    		 * 
    		 */
    		private static final long serialVersionUID = -7946690694369283250L;
    
    		public TokenValidationException(String msg) {
    			super(msg);
    		}
    	}
    }
    

      服务端登录验证成功生成jwtToken

    String accessToken = JwtUtil.generateToken(ucUser.getUserName());
    

      客户端发送请求,过滤器拦截请求验证jwtToken

    JwtUtil.validateToken(osptoken);
    

      

  • 相关阅读:
    maven创建父子工程
    webservice之jersey简单实用
    EL表达式处理字符串
    oracle不等于1怎么查?
    day_07 搭建Tomcat服务器使用Servlet服务,后端接受前端请求过来的表单数据并使用
    Day_06 流程控制-循环结构-嵌套循环结构的原理解析
    Day05_流程控制02 循环结构
    day_5 流程控制 选择结构的两种常用语句的使用语法
    day_04 运算符详解
    day_03 变量的数据类型详解
  • 原文地址:https://www.cnblogs.com/zhangmingcheng/p/7563431.html
Copyright © 2020-2023  润新知