之前看过一些文章,直接说不清楚,因为我也是第一次研究单点登录,所有自己想写一篇希望能有所帮助
dome地址:
0.准备工作
1.简介
json web token(JWT)是一种新的用户认证方式,不同与以前的Session.
JWT不需要服务器端存储用户信息,当用户登录后,服务器将用户信息放入加密放入token(token会被客户端保存),需要时再通过对token解密获取(客户请求时携带token)
2.代码
下面提供一种JWT的简单实现.这个例子实现的功能是:
1) 用户访问login.jsp进行登录操作.
则发放给用户本地浏览器的token为:eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwiaWF0IjoxNTIyMjUzMTIwLCJzdWIiOiLmtYvor5XnlKjmiLcxIiwiZXhwIjoxNTIyMjUzNzIwfQ.5jWbc4yP11Qfz1T5HHAjFpgNWCtYyTwOmMB8rTZAY4s
2) 用户访问myServlet时,若用户已登录则跳转至info.jsp显示用户名,未登录则跳转至login.jsp.地址后面一定要有参数,不然是post请求
在token有效期间,再次访问http://localhost:8080/jwt_demo/Servlet/myServlet?1=1
进行一次get请求,返回正常
3)打开另外一个浏览器,也是用账号test1登录,登录成功之后转到第一个浏览器,继续执行http://localhost:8080/jwt_demo/Servlet/myServlet?1=1
因为在另外一个浏览器登录过了,所以发送请求肯定被拦截器拦截,跳到登录页面
4.直接上代码吧
login.jsp
<%@ 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
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 javax.servlet.http.HttpSession;
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<Integer,User> users = new HashMap<>();
@Override
public void init() throws ServletException {
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#HttpServlet()
*/
public MyServlet() {
super();
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
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 {
//response.getWriter().append("Served at: ").append(request.getContextPath());
HttpSession session = request.getSession();
// 验证用户
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());
String token = session.getAttribute("token").toString();
//单点登录,取出每次登录保存的token,因为每次登录的token都是不一样的,如果客户端传过来的token可服务器取出来的token不一样
//则已经登录过,退出登录
//比如用户A在谷歌浏览器登录,保存的token是1234,A还没有退出,A一直访问后台带的token都是1234,A又在另外一个浏览器火狐登录这下token肯定又改变了
//因为每次token都是加密的,这里使用session保存token,A在谷歌浏览器传过来的的token依然是1234,但是后台session保存的token在火狐浏览器登录之后
//就改变了,取出浏览器发送请求带的token和session中的对比,如果一样调到登录页面,因为已经在另外一个浏览器登录。这就是单点登录
if(!token.equals(cookies[i].getValue())){
System.out.println("单点登录");
request.getRequestDispatcher("../login.jsp").forward(request, response);
return;
}
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) {
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 IOException {
String account = request.getParameter("account");
String password = request.getParameter("password");
HttpSession session = request.getSession();
System.out.println(account + " : " + password);
String token = "";
for(Entry<Integer, User> item : users.entrySet()){
User u = item.getValue();
//if条件写死代码做了授权,后期有时间可以配在web.xml中作授权认证
if(u.getAccount().equals(account)
&&u.getPassword().equals(password)){
try {
System.out.println(u.getName());
//将token 失效时间改为 60秒
token = JWTUtil.createJWT(String.valueOf(u.getId()), u.getName(), 1000*60);
session.setAttribute("token", token);
// 将token放进Cookie
Cookie cookie = new Cookie("JWT", token);
cookie.setPath("/");
// 设置cookie如果为负数,
// 该Cookie为临时Cookie,关闭浏览器即失效,浏览器也不会以任何形式保存该Cookie。
// 如果为0,表示删除该Cookie。默认为–1
cookie.setMaxAge(-1);
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
}
PrintWriter pw = response.getWriter();
if(!token.equals("")){
System.out.println(token);
pw.print("login succeeded : " + 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"%>
<!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
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;
}
}
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.hxuhao.servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/Servlet/myServlet</url-pattern>
</servlet-mapping>
</web-app>
来源:CSDN
作者:hexu_blog
链接:https://blog.csdn.net/hexu_blog/article/details/90701930