如今的app每每会有登陆功能,通常移动端app登陆后都会获得一个token,今天就将token的一种实现方式Json Web Token(JWT),对于不了解JWT的同窗能够参考这里,这里还有一个在线的的JWT生成器。html
在java中要使用jwt,须要pom.xml中添加以下依赖java
- <dependency>
- <groupId>com.auth0</groupId>
- <artifactId>java-jwt</artifactId>
- <version>2.2.0</version>
- </dependency>
首先建立工具类JWT
具体代码以下:git
- package com.xt.tutorial.utils;
-
- import java.util.HashMap;
- import java.util.Map;
-
- import com.auth0.jwt.JWTSigner;
- import com.auth0.jwt.JWTVerifier;
- import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
-
- public class JWT {
-
- private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";
-
- private static final String EXP = "exp";
-
- private static final String PAYLOAD = "payload";
-
-
-
-
-
-
-
-
-
- public static <T> String sign(T object, long maxAge) {
- try {
- final JWTSigner signer = new JWTSigner(SECRET);
- final Map<String, Object> claims = new HashMap<String, Object>();
- ObjectMapper mapper = new ObjectMapper();
- String jsonString = mapper.writeValueAsString(object);
- claims.put(PAYLOAD, jsonString);
- claims.put(EXP, System.currentTimeMillis() + maxAge);
- return signer.sign(claims);
- } catch(Exception e) {
- return null;
- }
- }
-
-
-
-
-
-
-
- public static<T> T unsign(String jwt, Class<T> classT) {
- final JWTVerifier verifier = new JWTVerifier(SECRET);
- try {
- final Map<String,Object> claims= verifier.verify(jwt);
- if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
- long exp = (Long)claims.get(EXP);
- long currentTimeMillis = System.currentTimeMillis();
- if (exp > currentTimeMillis) {
- String json = (String)claims.get(PAYLOAD);
- ObjectMapper objectMapper = new ObjectMapper();
- return objectMapper.readValue(json, classT);
- }
- }
- return null;
- } catch (Exception e) {
- return null;
- }
- }
- }
新建UsersController用于测试登陆github
建立User模型web
UsersController代码以下spring
- package com.xt.tutorial.v1.controllers;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.PostMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import com.xt.tutorial.models.User;
- import com.xt.tutorial.utils.JWT;
- import com.xt.tutorial.utils.ResponseData;
-
- @Controller
- @RequestMapping("/users")
- public class UsersController {
-
- @PostMapping("/login")
- @ResponseBody
- public ResponseData login(@RequestParam String username, @RequestParam String password) {
- if ("imjack".equals(username) && "123456".equals(password)) {
- ResponseData responseData = ResponseData.ok();
- User user = new User();
- user.setId(1);
- user.setUsername(username);
- user.setPassword(password);
- responseData.putDataValue("user", user);
- String token = JWT.sign(user, 30L * 24L * 3600L * 1000L);
- if (token != null) {
- responseData.putDataValue("token", token);
- }
- return responseData;
- }
- return ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, new String[] { "用户名或者密码错误" });
- }
- }
User模型代码以下
- package com.xt.tutorial.models;
-
- public class User {
- private long id;
- private String username;
- private String password;
-
- public long getId() {
- return id;
- }
-
- public void setId(long id) {
- this.id = id;
- }
-
- public String getUsername() {
- return username;
- }
-
- public void setUsername(String username) {
- this.username = username;
- }
-
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
- }
右击项目【Run As->Maven build】运行项目
为了验证咱们的JWT是否真的能够工做,咱们再设计一个MeController里面有一个get_info接口json
具体代码以下app
- package com.xt.tutorial.v1.controllers;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import com.xt.tutorial.models.User;
- import com.xt.tutorial.utils.JWT;
- import com.xt.tutorial.utils.ResponseData;
-
- @Controller
- @RequestMapping("/me")
- public class MeController {
-
- @GetMapping("/get_info")
- @ResponseBody
- public ResponseData getInfo(@RequestParam String token) {
- User user = JWT.unsign(token, User.class);
- if (user != null) {
- return ResponseData.ok().putDataValue("user", user);
- }
- return ResponseData.customerError().putDataValue(ResponseData.ERRORS_KEY, new String[] { "token不合法" });
- }
- }
右击项目【Run As->Maven build】运行项目
ide
这样一个简单完整的jwt就完成了,下一篇将继续介绍jwt工具
项目完整地址:https://github.com/imchenglibin/spring-web-tutorial
文章转载自:https://blog.csdn.net/jackcheng_ht/article/details/52670211