json web token的简单实现 JAVA

1.简介

json web token(JWT)是一种新的用户认证方式,不同与以前的Session.

JWT不需要服务器端存储用户信息,当用户登录后,服务器将用户信息放入加密放入token,需要时再通过对token解密获取.

关于更多JWT的介绍请自行搜索,这里提供一篇便于理解的文章: http://www.tuicool.com/articles/uuAzAbU 八幅漫画理解使用JSON Web Token设计单点登录系统

2.代码

下面提供一种JWT的简单实现.这个例子实现的功能是:

1) 用户访问login.jsp进行登录操作.

2) 用户访问myServlet时,若用户已登录则跳转至info.jsp显示用户名,未登录则跳转至login.jsp.


ps:这个demo是基于最基本的serlvet,jsp实现的,仅供参考,实际开发中并不会这么玩~



login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


帐号: 密码:

MyServlet.java

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;
       	// 模拟的数据库
	private HashMap 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 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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


Hello,<%=request.getAttribute("username") %>


JWTUtil.java

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;
	}
}

3.凑数

1.整个demo以上传github :  Hxuhao233 .需要的可以去看看(应该没人去吧2333333)

你可能感兴趣的:(JavaWeb)