jwt认证
Posted hitenine
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jwt认证相关的知识,希望对你有一定的参考价值。
JWT
json web token
maven依赖 java jwt
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
@Test
public void test03() {
JwtBuilder jwtBuilder = Jwts.builder()
.setId("66")
.setSubject("用户信息")
.setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "secret") //密钥不能太短 也不能为中文 否则报错
.claim("key","value")
.claim("could","many");
String token = jwtBuilder.compact(); //创建
System.out.println(token);
}
@Test
public void test033() {
String token = "token";
Claims claims = Jwts.parser().setSigningKey("secret").parseClaimsJws(token).getBody();
// 私有数据存放在clasims中
System.out.println(claims.getId());
System.out.println(claims.getSubject());
System.out.println(claims.getIssuedAt());
//解析自定义claims中的内容
System.out.println(claims.get("key"));
System.out.println(claims.get("could"));
}
暂不完美的工具类
@Data
@ConfigurationProperties(prefix = "jwt.config")
@Component
public class JwtUtils {
/**
* 签名的私钥
*/
private String key;
/**
* 签名时效的时间 time to live
*/
private Long ttl;
/**
* 设置认证token
* id: 登录用户id
* subject: 登陆的用户名
*/
public String createToken(String id, String name, Map<String, Object> map) {
//设置时下时间
long now = System.currentTimeMillis(); //当前毫秒
long exp = now + ttl;
//创建jwtbuilder
JwtBuilder jwtBuilder = Jwts.builder()
.setId(id)
.setSubject(name)
.setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, key);
//根据map设置claims
for (Map.Entry<String, Object> entry : map.entrySet()) {
jwtBuilder.claim(entry.getKey(),entry.getValue());
}
//设置失效时间
jwtBuilder.setExpiration(new Date(exp));
//创建token
return jwtBuilder.compact();
}
public String createToken(String id, String name) {
//设置时下时间
long now = System.currentTimeMillis(); //当前毫秒
long exp = now + ttl;
//创建jwtbuilder
JwtBuilder jwtBuilder = Jwts.builder()
.setId(id)
.setSubject(name)
.setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, key);
//设置失效时间
jwtBuilder.setExpiration(new Date(exp));
//创建token
return jwtBuilder.compact();
}
/**
* 解析token字符串获取claims
*/
public Claims parseJwt(String token) {
Claims claims = Jwts.parser().
setSigningKey(key)
.parseClaimsJws(token)
.getBody();
return claims;
}
}
@Autowired
private JwtUtils jwtUtils;
@PostMapping("/login")
@ResponseBody
public String login(@RequestBody Map<String,String> loginMap) {
String username = loginMap.get("username");
String password = loginMap.get("password");
User user = userMapper.selectById(1);
HashMap<String, Object> map = new HashMap<>();
if (user == null || !user.getPassword().equals(password)) {
map.put("msg", "用户名或密码错误");
return JSON.toJSONString(map);
} else {
map.put("nickname", user.getNickname());
System.out.println(String.valueOf(user.getId()));
String token = jwtUtils.createToken(String.valueOf(user.getId()), user.getUsername(), map);
map.put("token", token);
map.put("msg", "success");
return JSON.toJSONString(map);
}
}
@ResponseBody
@PostMapping("/profile")
public String profile(HttpServletRequest request) {
HashMap<String, Object> map = new HashMap<>();
String authorization = request.getHeader("Authorization");
if (StringUtils.isEmpty(authorization)) {
map.put("msg", "请登录");
return JSON.toJSONString(map);
}
String token = authorization.replace("Bearer", "");
Claims claims = jwtUtils.parseJwt(token);
String id = claims.getId();
System.out.println(id);
User user = userMapper.selectById(1);
// map.put("token", token);
map.put("msg", "success");
map.put("user", user);
return JSON.toJSONString(map);
}
配置拦截器使用
拦截器
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {
@Autowired
private JwtUtils jwtUtils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 1.通过request获取请求token信息
String authorization = request.getHeader("Authorization");
// 判断请求头信息是否为空,或者是否以Bearer开头
if (!StringUtils.isEmpty(authorization) && authorization.startsWith("Bearer")) {
// 获取token数据
String token = authorization.replace("Bearer", "");
Claims claims = jwtUtils.parseJwt(token);
if (claims != null) {
request.setAttribute("user_claims", claims);
return true;
}
}
//抛出异常
System.out.println("未登录");
return false;
}
}
配置
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Autowired
private JwtInterceptor jwtInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**") //指定拦截的url地址
.excludePathPatterns("/login","/register/**"); //指定不拦截的url地址
}
}
controller
@ResponseBody
@PostMapping("/profile")
public String profile(HttpServletRequest request) {
HashMap<String, Object> map = new HashMap<>();
Claims claims = (Claims)request.getAttribute("user_claims");
// String authorization = request.getHeader("Authorization");
// if (StringUtils.isEmpty(authorization)) {
// map.put("msg", "请登录");
// return JSON.toJSONString(map);
// }
// String token = authorization.replace("Bearer", "");
// Claims claims = jwtUtils.parseJwt(token);
String id = claims.getId();
System.out.println(id);
User user = userMapper.selectById(1);
// map.put("token", token);
map.put("msg", "success");
map.put("user", user);
return JSON.toJSONString(map);
}
以上是关于jwt认证的主要内容,如果未能解决你的问题,请参考以下文章