1.简介 json web token(JWT)是一种新的用户认证方式,不同与以前的Session.
JWT不需要服务器端存储用户信息,当用户登录后,服务器将用户信息放入加密放入token(token会被客户端保存),需要时再通过对token解密获取(客户请求时携带token)
2.代码 下面提供一种JWT的简单实现.这个例子实现的功能是:
####1) 用户访问login.jsp进行登录操作.
####2) 用户访问myServlet时,若用户已登录则跳转至info.jsp显示用户名,未登录则跳转至login.jsp.
ps:这个demo是基于最基本的serlvet,jsp实现的,仅供参考,实际开发中并不会这么玩~
login.jsp
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Servlet/myServlet" method="post">
帐号:<input type="text" name="account">
密码:<input type="password" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
MyServlet.java
代码语言:javascript复制package com.hxuhao.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hxuhao.model.User;
import com.hxuhao.utils.JWTUtil;
import io.jsonwebtoken.Claims;
/**
* Servlet implementation class MyServlet
*/
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
<span style="white-space:pre;"> </span>// 模拟的数据库
private HashMap<Integer,User> users = new HashMap<>();
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
super.init();
users.put(Integer.valueOf(1), new User(1,"test1","123","测试用户1"));
users.put(Integer.valueOf(2), new User(2,"test2","123","测试用户2"));
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
if(request.getMethod().equals("POST")){
doPost(request, response);
}else{
doGet(request, response);
}
}
/**
* 查看信息
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
// 验证用户
Cookie[] cookies = request.getCookies();
//User user=null;
String username = null;
if(cookies!=null){
for(int i=0;i<cookies.length;i ){
System.out.println(cookies[i].getName() " : " cookies[i].getValue());
if(cookies[i].getName().equals("JWT")){
Cookie cookie = cookies[i];
try {
// 检查token
Claims claims = JWTUtil.parseJWT(cookie.getValue());
username = claims.getSubject();
System.out.println("name : " username);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
if(username!=null){
request.setAttribute("username", username);
request.getRequestDispatcher("../info.jsp").forward(request, response);
}else{
//System.out.println("SendRedirect");
response.sendRedirect("../login.jsp");
}
}
/**
* 登录
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String account = request.getParameter("account");
String password = request.getParameter("password");
System.out.println(account " : " password);
String token = "";
for(Entry<Integer, User> item : users.entrySet()){
User u = item.getValue();
if(u.getAccount().equals(account)
&&u.getPassword().equals(password)){
try {
System.out.println(u.getName());
token = JWTUtil.createJWT(String.valueOf(u.getId()), u.getName(), 1000*60*10);
// 将token放进Cookie
Cookie cookie = new Cookie("JWT", token);
cookie.setPath("/");
// 过期时间设为10min
cookie.setMaxAge(60*10);
response.addCookie(cookie);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
PrintWriter pw = response.getWriter();
if(!token.equals("")){
System.out.println(token);
pw.print("login succeed : " token);
}
else{
pw.print("login failed : error account or password");
}
pw.flush();
pw.close();
}
}
info.jsp
代码语言:javascript复制<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Hello,<%=request.getAttribute("username") %></h2>
</body>
</html>
JWTUtil.java
代码语言:javascript复制package com.hxuhao.utils;
import java.util.Date;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
public class JWTUtil {
private static final String profiles="hxhxhxhxh";
/**
* 由字符串生成加密key
* @return
*/
private static SecretKey generalKey(){
String stringKey = profiles;
byte[] encodedKey = Base64.decodeBase64(stringKey);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
return key;
}
/**
* 创建jwt
* @param id
* @param subject
* @param ttlMillis
* @return
* @throws Exception
*/
public static String createJWT(String id, String subject, long ttlMillis) throws Exception {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
SecretKey key = generalKey();
JwtBuilder builder = Jwts.builder()
.setId(id)
.setIssuedAt(now)
.setSubject(subject)
.signWith(signatureAlgorithm, key);
if (ttlMillis >= 0) {
long expMillis = nowMillis ttlMillis;
Date exp = new Date(expMillis);
builder.setExpiration(exp);
}
return builder.compact();
}
/**
* 解析jwt
* @param jwt
* @return
* @throws Exception
*/
public static Claims parseJWT(String jwt) throws Exception{
SecretKey key = generalKey();
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt).getBody();
return claims;
}
}