JWT的简单实现(简单示例)

2018-08-23更新:

了解到新的jwt生成和解析方式。

pom.xml

<dependency>
	<groupId>io.jsonwebtoken</groupId>
	<artifactId>jjwt</artifactId>
	<version>0.7.0</version>
</dependency>

生成解析方法:

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * Created by 孙乐进 on 2018/8/9.
 */
@RestController
@RequestMapping("/api")
public class JwtUtil {

    private static final String JWTSECRET = "myScrect";
    /**
     * 生成jwt
     * @param userId
     * @return
     */
    @GetMapping("/jwt/create/{userId}")
    public static String createToken(@PathVariable  String userId) {
        String token = Jwts.builder()
                .setSubject(userId)
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000 * 365))
                .signWith(SignatureAlgorithm.HS512, JWTSECRET)
                .compact();
        return token;
    }

    //解析jwt
    @GetMapping("/jwt/verify/{token}")
    public static String verifyToken(@PathVariable String token){
        String user = Jwts.parser()
                .setSigningKey(JWTSECRET)
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
        return user;
    }

}

最近在学习使用springcloud的时候碰到session不好跨服务器(redis可实现),所以想着整合springSecurity+springboot+jwt,实现无状态身份认证。

------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 

pom.xml

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.1.0</version>
</dependency>

 

JWT生成:

    private static String SECRET = "mysecret";

    @GetMapping("/jwt/create/{info}")
    public static String createToken(@PathVariable String info) throws UnsupportedEncodingException {
        Date iatDate = new Date();
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,100);
        Date expiresDate = nowTime.getTime();

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("alg","HS256");
        map.put("type","JWT");
        String token = JWT.create().withHeader(map)
                .withClaim("info",info)
                .withExpiresAt(expiresDate)
                .withIssuedAt(iatDate)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

 

JWT解析:

    @GetMapping("/jwt/analyze/{token}")
    public static String verifyToken(@PathVariable String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        DecodedJWT jwt = null;
        jwt = verifier.verify(token);
        Map<String,Claim> result = jwt.getClaims();

        jwt.getKeyId() ;
        jwt.getToken();
        jwt.getClaim("info").asString();

        return result.get("info").asString();
    }

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐闻x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值