/** * Get the user profile from the credentials. * * @param credentials * @return the user profile */ @Override protected CasProfile retrieveUserProfile( final CasCredentials credentials, final WebContext context) { final String ticket = credentials.getServiceTicket(); try { final String contextualCallbackUrl = getContextualCallbackUrl(context); final Assertion assertion = this.ticketValidator.validate(ticket, contextualCallbackUrl); final AttributePrincipal principal = assertion.getPrincipal(); logger.debug("principal : {}", principal); final CasProfile casProfile; if (this.casProxyReceptor != null) { casProfile = new CasProxyProfile(); } else { casProfile = new CasProfile(); } casProfile.setId(principal.getName()); casProfile.addAttributes(principal.getAttributes()); if (this.casProxyReceptor != null) { ((CasProxyProfile) casProfile).setPrincipal(principal); } logger.debug("casProfile : {}", casProfile); return casProfile; } catch (final TicketValidationException e) { logger.error("cannot validate CAS ticket : {} / {}", ticket, e); throw new TechnicalException(e); } }
/** * This method verify the ticket. * * @param ticket String, ticket to validate * @param userId String, user id * @return String * @throws SecurityException the security exception */ public void validateTicket(String ticket, String userId) throws SecurityException { logger.debug("IN"); ConfigSingleton config = ConfigSingleton.getInstance(); String validateUrl = null; String validateService = null; if (config != null) { // only server side... validateUrl = SingletonConfig.getInstance().getConfigValue("CAS_SSO.VALIDATE-USER.URL"); logger.debug("Read validateUrl=" + validateUrl); validateService = SingletonConfig.getInstance().getConfigValue("CAS_SSO.VALIDATE-USER.SERVICE"); logger.debug("Read validateService=" + validateService); } logger.debug("userId:" + userId); try { AttributePrincipal principal = null; Cas20ProxyTicketValidator sv = new Cas20ProxyTicketValidator(validateUrl); sv.setAcceptAnyProxy(true); Assertion a = sv.validate(ticket, validateService); principal = a.getPrincipal(); logger.debug("Ticket is VALID, username="******"An exception occured while validating the cas token"); throw new SecurityException("An exception occured while validating the cas token", e); } catch (Throwable e) { logger.error("An exception occured while validating the cas token"); throw new SecurityException("An exception occured while validating the cas token", e); } finally { logger.debug("OUT"); } }
/** * 过滤逻辑:首先判断单点登录的账户是否已经存在本系统中, 如果不存在使用用户查询接口查询出用户对象并设置在Session中 * * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain) */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest httpRequest = (HttpServletRequest) request; // _const_cas_assertion_是CAS中存放登录用户名的session标志 Object object = httpRequest.getSession().getAttribute("_const_cas_assertion_"); if (object != null) { Assertion assertion = (Assertion) object; String loginName = assertion.getPrincipal().getName(); // 第一次登录系统 if (httpRequest.getSession().getAttribute("userid") == null) { System.out.println(loginName + "第一次登录"); UserOBJ visitor = Authentication.checkUser(loginName); HttpSession session = httpRequest.getSession(); session.setAttribute("userid", loginName); // 用户ID session.setAttribute("username", visitor.username); // 姓名 session.setAttribute("groupid", visitor.groupid); // 机构ID session.setAttribute("groupname", visitor.groupname); // 机构名称 session.setAttribute("pid", visitor.pid); // 上级机构ID session.setAttribute("pname", visitor.pname); // 上级机构名称 session.setAttribute("jgcode", visitor.jgcode); // 营销机构代码 session.setAttribute("station", visitor.station); // 银保机构代码 session.setAttribute("mobile", visitor.mobile); // 手机号码 session.setAttribute("phone", visitor.phone); // 座机电话 } } // pass the request along the filter chain chain.doFilter(request, response); }
public final String getCasServiceToken(final String target) throws CasProxyTicketAcquisitionException { if (log.isTraceEnabled()) { log.trace( "Attempting to retrieve proxy ticket for target [" + target + "] by using CAS Assertion [" + assertion + "]"); } if (this.assertion == null) { if (log.isDebugEnabled()) { log.debug("No Assertion found for user. Returning null Proxy Ticket."); } return null; } final String proxyTicket = this.assertion.getPrincipal().getProxyTicketFor(target); if (proxyTicket == null) { log.error( "Failed to retrieve proxy ticket for assertion [" + assertion + "]. Is the PGT still valid?"); throw new CasProxyTicketAcquisitionException(target, assertion.getPrincipal()); } if (log.isTraceEnabled()) { log.trace("Returning from Proxy Ticket Request with ticket [" + proxyTicket + "]"); } return proxyTicket; }
/** * Read user id. * * @param session HttpSession * @return String */ public String readUserIdentifier(HttpServletRequest request) { HttpSession session = request.getSession(); Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); String userInSession = assertion.getPrincipal().getName(); // String user=(String)request.getRemoteUser(); // logger.debug("CAS user in HttpServletRequest:"+user); logger.debug("CAS user in HttpSession:" + userInSession); return userInSession; }
public void validateTicket(HttpServletRequest httpRequest, String ticket) throws Exception { Cas20ProxyTicketValidator ticketValidator = new Cas20ProxyTicketValidator(casServerUrl); ticketValidator.setRenew(this.renewTicket); // String serviceUrl = "http://"+ httpRequest.getServerName() +":" + httpRequest.getServerPort() // + // httpRequest.getContextPath() +"/private/classic"; Assertion assertion = ticketValidator.validate(ticket, this.casServiceUrl); log.debug( "------------------------------------------------------------------------------------"); log.debug("Service: " + this.casServiceUrl); log.debug("Principal: " + assertion.getPrincipal().getName()); log.debug( "------------------------------------------------------------------------------------"); String principal = assertion.getPrincipal().getName(); this.saveSSOCredentials(principal, httpRequest); }
public CasProfile validateServiceTicket(final String serviceURL, final TokenCredentials ticket) { try { final Assertion assertion = getCasRestAuthenticator().getTicketValidator().validate(ticket.getToken(), serviceURL); final AttributePrincipal principal = assertion.getPrincipal(); final CasProfile casProfile = new CasProfile(); casProfile.setId(principal.getName()); casProfile.addAttributes(principal.getAttributes()); return casProfile; } catch (final TicketValidationException e) { throw new TechnicalException(e); } }
@SuppressWarnings("unchecked") @Override protected UserDetails loadUserDetails(final Assertion assertion) { final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(); for (final String attribute : this.attributes) { final Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value == null) { continue; } if (value instanceof List) { final List list = (List) value; for (final Object o : list) { grantedAuthorities.add( new SimpleGrantedAuthority( this.convertToUpperCase ? o.toString().toUpperCase() : o.toString())); } } else { grantedAuthorities.add( new SimpleGrantedAuthority( this.convertToUpperCase ? value.toString().toUpperCase() : value.toString())); } } return new User( assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities); }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setStatus(200); PrintWriter pw = new PrintWriter(response.getWriter()); pw.write("Hello World - This is the proxied application speaking (Backend)\n"); if (request.getUserPrincipal() != null) { pw.write( "Request.getUserPrincipal().getName(): " + request.getUserPrincipal().getName() + "\n"); } pw.write("Request.getRemoteUser(): " + request.getRemoteUser() + "\n"); for (Cookie cookie : request.getCookies()) { pw.write( "Cookie - Name: " + cookie.getName() + " Domain: " + cookie.getDomain() + " Path: " + cookie.getPath() + " Value: " + cookie.getValue() + "\n"); } Assertion assertion = AssertionHolder.getAssertion(); if (assertion != null) { pw.write("\n"); pw.write("Assertion: " + assertion.getPrincipal().getName()); for (Object key : assertion.getPrincipal().getAttributes().keySet()) { String value = (String) assertion.getPrincipal().getAttributes().get(key); pw.write("Attribute: " + key + " " + value + "\n"); } } else { pw.write("Assertion is null\n"); } }
/** * Get a new ticket. * * @param session HttpSession * @return String * @throws IOException Signals that an I/O exception has occurred. */ public String readTicket(HttpSession session) throws IOException { logger.debug("IN"); String ticket = null; String spagoBiServerURL = EnginConf.getInstance().getSpagoBiServerUrl(); logger.debug("Read spagoBiServerURL=" + spagoBiServerURL); SourceBean engineConfig = EnginConf.getInstance().getConfig(); SourceBean sourceBeanConf = (SourceBean) engineConfig.getAttribute("FILTER_RECEIPT"); String filterReceipt = (String) sourceBeanConf.getCharacters(); logger.debug("Read filterReceipt=" + filterReceipt); filterReceipt = spagoBiServerURL + filterReceipt; Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); ticket = assertion.getPrincipal().getProxyTicketFor(filterReceipt); logger.debug("OUT.ticket=" + ticket); return ticket; }
/** * Authenticates a user and retrieves its information. * * @param token the authentication token * @throws AuthenticationException if there is an error during authentication. */ @Override @SuppressWarnings("unchecked") protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { CasToken casToken = (CasToken) token; if (token == null) { return null; } String ticket = (String) casToken.getCredentials(); if (!StringUtils.hasText(ticket)) { return null; } TicketValidator ticketValidator = ensureTicketValidator(); try { // contact CAS server to validate service ticket Assertion casAssertion = ticketValidator.validate(ticket, getCasService()); // get principal, user id and attributes AttributePrincipal casPrincipal = casAssertion.getPrincipal(); String userId = casPrincipal.getName(); log.debug( "Validate ticket : {} in CAS server : {} to retrieve user : {}", new Object[] {ticket, getCasServerUrlPrefix(), userId}); Map<String, Object> attributes = casPrincipal.getAttributes(); // refresh authentication token (user id + remember me) casToken.setUserId(userId); String rememberMeAttributeName = getRememberMeAttributeName(); String rememberMeStringValue = (String) attributes.get(rememberMeAttributeName); boolean isRemembered = rememberMeStringValue != null && Boolean.parseBoolean(rememberMeStringValue); if (isRemembered) { casToken.setRememberMe(true); } // create simple authentication info List<Object> principals = CollectionUtils.asList(userId, attributes); PrincipalCollection principalCollection = new SimplePrincipalCollection(principals, getName()); return new SimpleAuthenticationInfo(principalCollection, ticket); } catch (TicketValidationException e) { throw new CasAuthenticationException("Unable to validate ticket [" + ticket + "]", e); } }
private AuthenticationInfo createAuthnInfo(final Assertion assertion) { AuthenticationInfo authnInfo; String username = assertion.getPrincipal().getName(); authnInfo = new AuthenticationInfo(AUTH_TYPE, username); return authnInfo; }
@Override protected void processFilter( HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws Exception { HttpSession session = request.getSession(); long companyId = PortalUtil.getCompanyId(request); String pathInfo = request.getPathInfo(); Object forceLogout = session.getAttribute(WebKeys.CAS_FORCE_LOGOUT); if (forceLogout != null) { session.removeAttribute(WebKeys.CAS_FORCE_LOGOUT); String logoutUrl = PrefsPropsUtil.getString(companyId, PropsKeys.CAS_LOGOUT_URL, PropsValues.CAS_LOGOUT_URL); response.sendRedirect(logoutUrl); return; } if (pathInfo.indexOf("/portal/logout") != -1) { session.invalidate(); String logoutUrl = PrefsPropsUtil.getString(companyId, PropsKeys.CAS_LOGOUT_URL, PropsValues.CAS_LOGOUT_URL); response.sendRedirect(logoutUrl); return; } else { String login = (String) session.getAttribute(WebKeys.CAS_LOGIN); String serverName = PrefsPropsUtil.getString( companyId, PropsKeys.CAS_SERVER_NAME, PropsValues.CAS_SERVER_NAME); String serviceUrl = PrefsPropsUtil.getString( companyId, PropsKeys.CAS_SERVICE_URL, PropsValues.CAS_SERVICE_URL); if (Validator.isNull(serviceUrl)) { serviceUrl = CommonUtils.constructServiceUrl( request, response, serviceUrl, serverName, "ticket", false); } String ticket = ParamUtil.getString(request, "ticket"); if (Validator.isNull(ticket)) { if (Validator.isNotNull(login)) { processFilter(CASFilter.class, request, response, filterChain); } else { String loginUrl = PrefsPropsUtil.getString( companyId, PropsKeys.CAS_LOGIN_URL, PropsValues.CAS_LOGIN_URL); loginUrl = HttpUtil.addParameter(loginUrl, "service", serviceUrl); response.sendRedirect(loginUrl); } return; } TicketValidator ticketValidator = getTicketValidator(companyId); Assertion assertion = ticketValidator.validate(ticket, serviceUrl); if (assertion != null) { AttributePrincipal attributePrincipal = assertion.getPrincipal(); login = attributePrincipal.getName(); session.setAttribute(WebKeys.CAS_LOGIN, login); } } processFilter(CASFilter.class, request, response, filterChain); }
@Override public final void authenticate() throws PortalSecurityException { if (log.isTraceEnabled()) { log.trace("Authenticating user via CAS."); } this.isauth = false; this.assertion = AssertionHolder.getAssertion(); if (this.assertion != null) { final String usernameFromCas = assertion.getPrincipal().getName(); if (null == usernameFromCas) { throw new IllegalStateException( "Non-null CAS assertion unexpectedly had null principal name."); } this.myPrincipal.setUID(usernameFromCas); // verify that the principal UID was successfully set final String uidAsSetInThePrincipal = this.myPrincipal.getUID(); if (!usernameFromCas.equals(uidAsSetInThePrincipal)) { final String logMessage = "Attempted to set portal principal username to [" + usernameFromCas + "] as read from the CAS assertion, but uid as set in the principal is instead [" + uidAsSetInThePrincipal + "]. This may be an attempt to exploit CVE-2014-5059 / UP-4192 ."; log.error(logMessage); throw new IllegalStateException(logMessage); } this.isauth = true; log.debug( "CASContext authenticated [" + this.myPrincipal.getUID() + "] using assertion [" + this.assertion + "]"); /* Patch needed for Shibboleth + Proxy CAS Authentication here */ /* //this.myPrincipal.setUID(assertion.getPrincipal().getName()); //this.isauth = true; //log.debug("CASContext authenticated [" + this.myPrincipal.getUID() + "] using assertion [" + this.assertion + "]"); log.info("patch RUNN - No real CAS Authentication : CASContext authenticated using assertion " + this.assertion); this.myPrincipal.setUID(assertion.getPrincipal().getName()); this.isauth = true; log.debug("CASContext authenticated [" + this.myPrincipal.getUID() + "] using assertion [" + this.assertion + "]"); */ postAuthenticate(assertion); } this.myAdditionalDescriptor = null; // no additional descriptor from CAS super.authenticate(); if (log.isTraceEnabled()) { log.trace("Finished CAS Authentication"); } }
/** * Read user id. * * @param session PortletSession * @return String */ public String readUserIdentifier(PortletSession session) { Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); String user = assertion.getPrincipal().getName(); logger.debug("CAS user in PortletSession:" + user); return user; }