三、后台实战——用户登录之JWT

现在的app往往会有登录功能,一般移动端app登录后都会得到一个token,今天就将token的一种实现方式Json Web Token(JWT),对于不了解JWT的同学可以参考这里,这里还有一个在线的的JWT生成器。

在java中要使用jwt,需要pom.xml中添加如下依赖


    com.auth0
    java-jwt
    2.2.0

首先创建工具类JWT


具体代码如下:

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<>?N<:{LWPW";
	
	private static final String EXP = "exp";
	
	private static final String PAYLOAD = "payload";

	/**
	 * get jwt String of object
	 * @param object
	 *            the POJO object
	 * @param maxAge
	 *            the milliseconds of life time
	 * @return the jwt token
	 */
	public static  String sign(T object, long maxAge) {
		try {
			final JWTSigner signer = new JWTSigner(SECRET);
			final Map claims = new HashMap();
			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;
		}
	}
	
	
	/**
	 * get the object of jwt if not expired
	 * @param jwt
	 * @return POJO object
	 */
	public static T unsign(String jwt, Class classT) {
		final JWTVerifier verifier = new JWTVerifier(SECRET);
	    try {
			final Map 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用于测试登录


创建User模型


UsersController代码如下

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接口


具体代码如下

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】运行项目


这样一个简单完整的jwt就完成了,下一篇将继续介绍jwt

项目完整地址:https://github.com/imchenglibin/spring-web-tutorial

你可能感兴趣的:(后台实战)