单点登录

原理:
1.通过数字签名对用户名签名,把签名放在cookie中,在另一个应用中验证这个签名
2.以上信息通过url直接传递参数
1.签名类
public class SecurityUtil {
public static final String PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAJLyPRvDVQhYA5gGlAvZZr1YCLFgSSWAB4fvSa8ViZo7OBWCJBdn73x5qTDgwwZY9FbBvpmz+wQQozLWAGfc2ecCAwEAAQ==";
public static final String PRIVATE_KEY = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAkvI9G8NVCFgDmAaUC9lmvVgIsWBJJYAHh+9JrxWJmjs4FYIkF2fvfHmpMODDBlj0VsG+mbP7BBCjMtYAZ9zZ5wIDAQABAkAUAmBH04VUqYdzwBGQu3298qrcXFwZeyGLZQ4HhUtDcO8Zli+Na25LzWCtizYOyO9PsTFKdFhMiJN+XaAed04BAiEA6wifzFBG2ph86oZOqK1CjmL4CHIzt4KXt4YHB5TqLqcCIQCgDf6nFESpR7YpaWXSdZLWnZlCnUyMdaDaCM2jcyaiwQIhAOHRJG+ShbELJ6HRLwwjg7n4XuUGjKf5YjmjHWfsbOArAiAqO6cfVTTM6jRB9yK8BvQpF0rSjgkd4wf/oGUKpR7jwQIhAIs81vXXHlLMHjTWQlUDh8gpGAvIORViBbeOvmb8OrLF";

public static String sign(String data) {
try {
Signature sig = Signature.getInstance("SHA1WithRSA");
BASE64Decoder decoder = new BASE64Decoder();
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
decoder.decodeBuffer(PRIVATE_KEY));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
sig.initSign(privateKey);
sig.update(data.getBytes());
BASE64Encoder encoder = new BASE64Encoder();
String signature = encoder.encode(sig.sign());
// log.info("signature=" + signature);
return signature.replaceAll("\r\n", "");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static boolean verify(String data, String signature) {
try {
Signature sig = Signature.getInstance("SHA1WithRSA");
BASE64Decoder decoder = new BASE64Decoder();
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(decoder
.decodeBuffer(PUBLIC_KEY));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
sig.initVerify(publicKey);
sig.update(data.getBytes());
boolean verify = sig.verify(decoder.decodeBuffer(signature));
// log.info("data=" + data + " signature=" + signature + " verify="
// + verify);
return verify;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}

2.Servlet:
public class LoginServlet extends HttpServlet {
private static Log log = LogFactory.getLog(LoginServlet.class);

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
log.info("userName=" + userName + " password=" + password);
if (userName.equals("admin") && password.equals("admin")) {
request.getSession().setAttribute("user", userName);
String sign = SecurityUtil.sign(userName.trim());
if (sign != null) {
Cookie unCookie = new Cookie("userName", userName);
unCookie.setMaxAge(60 * 30);
unCookie.setPath("/");
response.addCookie(unCookie);

Cookie signCookie = new Cookie("sign", sign);
signCookie.setMaxAge(60 * 30);
signCookie.setPath("/");

response.addCookie(signCookie);
}
log.info("userName=" + userName + " sign=" + sign);
response.sendRedirect(request.getContextPath() + "/main.jsp");
// RequestDispatcher dispatcher = getServletContext()
// .getRequestDispatcher("/main.jsp");
// dispatcher.forward(request, response);
} else {
request.setAttribute("errorMsg", "登录失败!");
RequestDispatcher dispatcher = getServletContext()
.getRequestDispatcher("/index.jsp");
dispatcher.forward(request, response);
}
}
}

3.index.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>登录</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/loginServlet" method="post">
<table style="padding: 0; margin: 0">
<%
if (request.getAttribute("errorMsg") != null) {
%>
<tr>
<td colspan=2 align=center><font color=red>${errorMsg}</font></td>
</tr>
<%
}
%>
<tr>
<td width=100 align=right>用户名:</td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td align=right>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan=2 align=center><input type="submit" value="登录" />  <input
type="reset" value="重置" /></td>
</tr>
</table>
</form>
</body>
</html>

4.main.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">
<%@page import="com.agor.weather.servlet.LoginServlet"%>
<%@page import="com.agor.weather.servlet.SecurityUtil"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>
</head>
<body>

<%
Cookie cookies[] = request.getCookies(); // 将适用目录下所有Cookie读入并存入cookies数组中
String userName = null;
String sign = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++)
{
Cookie cookie = cookies[i];
out.println("cname="+cookie.getName()+" cvalue="+cookie.getValue()+"<br/>");
if (cookie.getName().equals("userName")) {
userName = cookie.getValue();
}
if (cookie.getName().equals("sign")) {
sign = cookie.getValue();
}
}
}
out.println("userName="+userName+" sign="+sign+"<br/>");
if (userName != null && sign != null) {
if (SecurityUtil.verify(userName, sign)) {
//System.out.println("login success from cookie");
request.getSession().setAttribute("user",userName);
}
}
if (request.getSession().getAttribute("user") == null) {
//this.getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);

} else {
%>
<h3>${user},欢迎您进入weather节点1应用</h3>
<br />
<a href="http://localhost:8080/weather2/main.jsp">节点2</a>
<%
}
%>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值