Web-sso原理网上自己搜,一堆,本文不给予讨论。
本人只给实例,通过实例去真实的感受Web-sso的原理。
不讨论太多的废话,开始web-sso实现。
1. 支持环境 jdk1.7 +tomcat7.0(具体自己网上搜,不会的)
2. 创建3个web工程。2个业务应用,1个认证应用。
1.创建web工程1名称 – SSOAuth(认证应用)
2.创建AuthServlet类:
package org.servlet;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.servlet.ServletConfig;
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;
@WebServlet(urlPatterns="/jsp/login.page",loadOnStartup=1)
publicclass AuthServlet extends HttpServlet {
/**
*Constructoroftheobject.
*/
public AuthServlet() {
super();
}
/**
*Destructionoftheservlet.<br>
*/
publicvoid destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DomainName= request.getSession().getServletContext().getInitParameter("DomainName");
CookName = request.getSession().getServletContext().getInitParameter("CookieName");
//验证码
String location =request.getContextPath()+"/login.jsp";
String ccode =(String) request.getSession().getAttribute("ccode");
String checkcode =request.getParameter("checkcode");
if(!checkcode.equals(ccode)){
response.sendRedirect(location);
}else{
String username =request.getParameter("username");
String userpassword =request.getParameter("userpassword");
String key =accounts.get(username);
if(key==null){
response.sendRedirect(location);
}else{
if(key.equals(userpassword)){ //验证通过
String gotoURL = request.getParameter("goto");
String sessionId =request.getSession().getId();
Cookie cookie =new Cookie(CookName,sessionId);
// cookie.setDomain(gotoURL);
cookie.setMaxAge(100);
// cookie.setValue(sessionId);
cookie.setPath("/");
response.addCookie(cookie);
if (gotoURL != null) {
response.sendRedirect(gotoURL);
}else{
response.sendRedirect(location);
}
}else{
response.sendRedirect(location);
}
}
}
}
/**
*Initializationoftheservlet.<br>
*
*@throwsServletExceptionifanerroroccurs
*/
staticprivate ConcurrentMap<String, String> accounts;
// static private ConcurrentMap SSOIDs;
String CookName;
String DomainName;
@Override
publicvoid init(ServletConfig config) throws ServletException {
// SSOIDs = new ConcurrentHashMap<String, String>();
accounts=new ConcurrentHashMap<String, String>();
accounts.put("joylife", "123456");
accounts.put("admin", "123456");
accounts.put("json", "123456");
}
}
3. 创建login.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String url =request.getParameter("goto");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>系统登录界面</title>
<script type="text/javascript" src="<%=path %>/js/jquery-1.7.1.min.js"></script>
<style type="text/css">
body {
font: normal 11px auto "Trebuchet MS", Verdana, Arial, Helvetica,
sans-serif;
color: #4f6b72;
/*background: #E6EAE9;*/
}
table {
margin-top: 10%;
margin-left: 30%;
border: 1px solid #CCCCFF;
}
table td {
border: 0px solid #CCCCFF;
font: bold 12px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #000000;
}
table input {
width: 200px;
}
.leftTd {
text-align: right;
width: 35%;
}
.centerTd {
text-align: center;
font: bold 18px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #000000;
}
.rightTd {
text-align: left;
width: 65%;
}
#btn_ok{
width: 50px;
}
#btn_clear{
width: 50px;
}
a{
margin:30px;
}
</style>
<script type="text/javascript">
$(function(){
$("#btn_reload").bind("click",function(){
btn_reload();
});
$("#btn_clear").bind("click",function(){
btn_clear();
});
$("#btn_ok").bind("click",function(){
btn_ok();
});
});
function btn_ok(){
var result =validateform();
if(!result){
return ;
}
$("#form").attr("action","jsp/login.page");
$("#form").submit();
}
function btn_reload(){
$("#image").removeAttr("src");
$("#image").attr("src","<%=path%>/image.jsp");
}
function btn_clear(){
$(":input").not("input[type=button]").each(function(){
$(this).val("");
});
}
function validateform(){
var result =true;
$(":input").not("input[type=button]").each(function(){
if($(this).val() ==""){
result=false;
}
});
return result ;
}
</script>
</head>
<body>
<form id="form" action="login.jsp" method="post">
<table>
<tbody>
<tr>
<td colspan="99" class="centerTd">
用户信息登录
</td>
</tr>
<tr>
<td class="leftTd">
<label>
用户名
</label>
</td>
<td class="rightTd">
<input type="text" name="username" />
</td>
</tr>
<tr>
<td class="leftTd">
<label>
密码
</label>
</td>
<td class="rightTd">
<input type="password" name="userpassword" />
</td>
</tr>
<tr>
<td class="leftTd">
<label>
验证码
</label>
</td>
<td class="rightTd">
<input type="text" name="checkcode" />
<img src="<%=path%>/image.jsp"id="image" />
</td>
</tr>
<tr >
<td class="leftTd">
<input type="button" id="btn_ok" value="登录" />
</td>
<td class="rightTd">
<input type="button" id="btn_clear" value="重置" />
<a href ="javascript:void(0);" id="btn_reload">验证码看不清点刷新</a>
</td>
</tr>
</tbody>
</table>
<input name="goto" type="hidden" value=<%=url%>/>
</form>
</body>
</html>
4 .创建 image.jsp
<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
Color getRandColor(int fc,int bc){
Random random = new Random();
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
returnnew Color(r,g,b);
}
%>
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}
String sRand="";
for (int i=0;i<4;i++){
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(rand,13*i+6,16);
}
session.setAttribute("ccode",sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
out.clear();
out = pageContext.pushBody();
%>
注意:Jquery文件自己搜下。
5. 配置Web.xml
<context-param>
<param-name>DomainName</param-name>
<param-value>10.1.4.94(改成自己的实际IP地址,不需要端口)</param-value>
</context-param>
<context-param>
<param-name>CookieName</param-name>
<param-value>XiaoHaibingDesktopSSOID</param-value>
</context-param>
创建web工程2 - SSOWebDemo1
1.创建 Index.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String SSOLoginPage =request.getSession().getServletContext().getInitParameter("SSOLoginPage");
String CookieName =request.getSession().getServletContext().getInitParameter("CookieName");
CookieName =CookieName.toLowerCase().trim();
Cookie[] cookies= request.getCookies();
Cookie loginCookie =null;
String cookname ="";
if(cookies!=null){
for(Cookie cookie:cookies){
cookname =cookie.getName().trim().toLowerCase();
if(CookieName.equals(cookname)){
loginCookie =cookie;
break;
}
}
}
if(loginCookie==null){
String url =request.getRequestURL().toString();
response.sendRedirect(SSOLoginPage+"?goto="+url);
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ssowebdemo1</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
WELCOME SsoWebDemo1 !<br>
</body>
</html>
2.web.xml配置
<context-param>
<param-name>CookieName</param-name>
<param-value>
XiaohaibingDesktopSSOID
</param-value>
</context-param>
<context-param>
<param-name>SSOLoginPage</param-name>
<param-value>
http://10.1.4.94(换成实际IP):8080/SSOAuth/login.jsp
</param-value>
</context-param>
工程3- SSOWebDemo2
1.创建 Index.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%
String SSOLoginPage =request.getSession().getServletContext().getInitParameter("SSOLoginPage");
String CookieName =request.getSession().getServletContext().getInitParameter("CookieName");
CookieName =CookieName.toLowerCase().trim();
Cookie[] cookies= request.getCookies();
Cookie loginCookie =null;
String cookname ="";
if(cookies!=null){
for(Cookie cookie:cookies){
cookname =cookie.getName().trim().toLowerCase();
if(CookieName.equals(cookname)){
loginCookie =cookie;
break;
}
}
}
if(loginCookie==null){
String url =request.getRequestURL().toString();
response.sendRedirect(SSOLoginPage+"?goto="+url);
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>ssowebdemo1</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
WELCOME SsoWebDemo2 !<br>
</body>
</html>
2.web.xml配置
<context-param>
<param-name>CookieName</param-name>
<param-value>
XiaohaibingDesktopSSOID
</param-value>
</context-param>
<context-param>
<param-name>SSOLoginPage</param-name>
<param-value>
http://10.1.4.94(换成实际IP):8080/SSOAuth/login.jsp
</param-value>
</context-param>