sso 实现

1、 共享cookie类(未完成)
(1)服务器端代码
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SSOAuth extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static  ConcurrentMap<String, String> accounts;
	private static  ConcurrentMap<String, String> SSOIDs;
    private String cookiename="WangYuDesktopSSOID";
    private String domainname="localhost";
    
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
       //domainname= config.getInitParameter("domainname");
        SSOIDs = new ConcurrentHashMap();
        accounts=new ConcurrentHashMap();
        accounts.put("1", "1");
        accounts.put("paul", "paul");
        accounts.put("carol", "carol");
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	PrintWriter out = response.getWriter();
        String action = request.getParameter("action");
        String result="failed";
        if (action==null) {
            handlerFromLogin(request,response);
        } else if (action.equals("authcookie")){
            String myCookie = request.getParameter("cookiename");
            if (myCookie != null) result = authCookie(myCookie);
          out.print(result);
           out.close();
        } else if (action.equals("authuser")) {
           result=authNameAndPasswd(request,response);
            out.print(result);
            out.close();
        } else if (action.equals("logout")) {
            String myCookie = request.getParameter("cookiename");
            log(myCookie);
           out.close();
        }
    }
    
    private String authNameAndPasswd(HttpServletRequest request,
			HttpServletResponse response) {
    	System.out.println("authNameAndPasswd");
		return null;
	}

	private String authCookie(String myCookie) {
		System.out.println("authCookie");
		return null;
	}

	private void handlerFromLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String pass = (String)accounts.get(username);
        if ((pass==null)||(!pass.equals(password)))
            getServletContext().getRequestDispatcher("/failed.html").forward(request, response);
        else {
            String gotoURL = "ok.jsp";
            String newID = createUID();
            SSOIDs.put(newID, username);
            Cookie wangyu = new Cookie(cookiename, newID);
            wangyu.setDomain(domainname);
            wangyu.setMaxAge(60000);
            wangyu.setValue(newID);
            wangyu.setPath("/");
            response.addCookie(wangyu);
            System.out.println("login success, goto back url:" + gotoURL);
            if (gotoURL != null) {
                response.sendRedirect(gotoURL);
            }
        }   
    }

	private String createUID() {
		return "1";
	}
}

(2)客户端代码
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SSOFilter implements Filter {

	private FilterConfig filterConfig = null;

	private String cookieName = "PASESSION";

	private String SSOServiceURL = "LoginServlet.do";

	private String SSOLoginPage = "login.html";

	public void destroy() {
		// TODO Auto-generated method stub
	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		String result = "failed";
		String cookieValue = "";
		javax.servlet.http.Cookie[] diskCookies = request.getCookies();
		if (diskCookies != null) {
			for (int i = 0; i < diskCookies.length; i++) {
				if (diskCookies[i].getName().equals(cookieName)) {
					cookieValue = diskCookies[i].getValue();
					result = SSOService(cookieValue);
				}
			}
		}
		if (result.equals("failed")) { // 效验失败或没有找到cookie,则需要登录
			response.sendRedirect(SSOLoginPage);
		} else {// 效验成功
			request.setAttribute("SSOUser", result);
			Throwable problem = null;
			try {
				chain.doFilter(req, res);
			} catch (Throwable t) {
				problem = t;
				t.printStackTrace();
			}
			if (problem != null) {
				if (problem instanceof ServletException)
					throw (ServletException) problem;
				if (problem instanceof IOException)
					throw (IOException) problem;
				// sendProcessingError(problem, res);
			}
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	private String SSOService(String cookievalue) throws IOException {
		return "ok";

		// HttpClient httpclient = new HttpClient();
		// GetMethod httpget = new
		// GetMethod(SSOServiceURL+authAction+cookievalue);
		// try {
		// httpclient.executeMethod(httpget);
		// String result = httpget.getResponseBodyAsString();
		// return result;
		// } finally {
		// httpget.releaseConnection();
		//
		// }

	}

	private void logoutService(String cookievalue) throws IOException {
		// String authAction = "?action=logout&cookiename=";
		// HttpClient httpclient = new HttpClient();
		// GetMethod httpget = new
		// GetMethod(SSOServiceURL+authAction+cookievalue);
		// try {
		// httpclient.executeMethod(httpget);
		// httpget.getResponseBodyAsString();
		// } finally {
		// httpget.releaseConnection();
		// }

	}

}


(3)pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.xxx</groupId>
	<artifactId>sso</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>sso Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<build>
	<finalName>sso</finalName>
		<plugins>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>tomcat-maven-plugin</artifactId>
				<version>1.1</version>
				<configuration>
					<server>tomcat-6.0.32</server>
					<url>http://127.0.0.1:8080/manager</url>
					<uriEncoding>${encoding}</uriEncoding>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.4</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>  
</project>


(4)web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.xxx.sso.SSOAuth</servlet-class>
  </servlet>

   <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet.do</url-pattern>
  </servlet-mapping>	

  	<filter>
		<filter-name>ssoFilter</filter-name>
		<filter-class>com.xxx.des.SSOFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>ssoFilter</filter-name>
		<url-pattern>*.jsp</url-pattern>
	</filter-mapping>
</web-app>

你可能感兴趣的:(SSO)