1 16 package org.mortbay.http; 17 18 import java.security.Principal ; 19 import java.security.SecureRandom ; 20 import java.util.HashMap ; 21 import java.util.Random ; 22 23 import javax.servlet.http.Cookie ; 24 25 import org.apache.commons.logging.Log; 26 import org.mortbay.log.LogFactory; 27 import org.mortbay.util.Credential; 28 29 30 public class HashSSORealm implements SSORealm 31 { 32 private static Log log = LogFactory.getLog(HashSSORealm.class); 33 34 35 public static final String SSO_COOKIE_NAME = "SSO_ID"; 36 private HashMap _ssoId2Principal = new HashMap (); 37 private HashMap _ssoUsername2Id = new HashMap (); 38 private HashMap _ssoPrincipal2Credential = new HashMap (); 39 private transient Random _random = new SecureRandom (); 40 41 42 public Credential getSingleSignOn(HttpRequest request, 43 HttpResponse response) 44 { 45 String ssoID = null; 46 Cookie [] cookies = request.getCookies(); 47 for (int i = 0; i < cookies.length; i++) 48 { 49 if (cookies[i].getName().equals(SSO_COOKIE_NAME)) 50 { 51 ssoID = cookies[i].getValue(); 52 break; 53 } 54 } 55 if(log.isDebugEnabled())log.debug("get ssoID="+ssoID); 56 57 Principal principal=null; 58 Credential credential=null; 59 synchronized(_ssoId2Principal) 60 { 61 principal=(Principal )_ssoId2Principal.get(ssoID); 62 credential=(Credential)_ssoPrincipal2Credential.get(principal); 63 } 64 65 if(log.isDebugEnabled())log.debug("SSO principal="+principal); 66 67 if (principal!=null && credential!=null) 68 { 69 if (response.getHttpContext().getRealm().reauthenticate(principal)) 70 { 71 request.setUserPrincipal(principal); 72 request.setAuthUser(principal.getName()); 73 return credential; 74 } 75 else 76 { 77 synchronized(_ssoId2Principal) 78 { 79 _ssoId2Principal.remove(ssoID); 80 _ssoPrincipal2Credential.remove(principal); 81 _ssoUsername2Id.remove(principal.getName()); 82 } 83 } 84 } 85 return null; 86 } 87 88 89 90 public void setSingleSignOn(HttpRequest request, 91 HttpResponse response, 92 Principal principal, 93 Credential credential) 94 { 95 96 String ssoID=null; 97 98 synchronized(_ssoId2Principal) 99 { 100 while (true) 102 { 103 ssoID = Long.toString(Math.abs(_random.nextLong()), 104 30 + (int)(System.currentTimeMillis() % 7)); 105 if (!_ssoId2Principal.containsKey(ssoID)) 106 break; 107 } 108 109 if(log.isDebugEnabled())log.debug("set ssoID="+ssoID); 110 _ssoId2Principal.put(ssoID,principal); 111 _ssoPrincipal2Credential.put(principal,credential); 112 _ssoUsername2Id.put(principal.getName(),ssoID); 113 } 114 115 Cookie cookie = new Cookie (SSO_COOKIE_NAME, ssoID); 116 cookie.setPath("/"); 117 response.addSetCookie(cookie); 118 } 119 120 121 122 public void clearSingleSignOn(String username) 123 { 124 synchronized(_ssoId2Principal) 125 { 126 Object ssoID=_ssoUsername2Id.remove(username); 127 Object principal=_ssoId2Principal.remove(ssoID); 128 _ssoPrincipal2Credential.remove(principal); 129 } 130 } 131 } 132 | Popular Tags |