Search in sources :

Example 1 with AttributePrincipal

use of org.jasig.cas.client.authentication.AttributePrincipal in project ddf by codice.

the class Query method getProxyTicket.

/**
     * Gets the CAS proxy ticket that will be used by the STS to get a SAML assertion.
     *
     * @param request The Http servlet request.
     * @return Returns the CAS proxy ticket that will be used by the STS to get a SAML assertion.
     */
private String getProxyTicket(HttpServletRequest request) {
    AttributePrincipal attributePrincipal = (AttributePrincipal) request.getUserPrincipal();
    String proxyTicket = null;
    if (attributePrincipal != null) {
        // proxyTicket = attributePrincipal.getProxyTicketFor(
        // "https://server:8993/ddf/query/sts" );
        LOGGER.debug("Getting proxy ticket for {}", STS_SERVICE_URL);
        proxyTicket = attributePrincipal.getProxyTicketFor(STS_SERVICE_URL);
        LOGGER.info("proxy ticket: {}", proxyTicket);
    } else {
        LOGGER.error("attribute principal is null!");
    }
    return proxyTicket;
}
Also used : AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal)

Example 2 with AttributePrincipal

use of org.jasig.cas.client.authentication.AttributePrincipal in project ddf by codice.

the class ExampleSSOWidget method createPage.

@SuppressWarnings("rawtypes")
protected void createPage(HttpServletRequest request, PrintWriter out) throws IOException, ServletException {
    String endl = System.getProperty("line.separator");
    StringBuilder sb = new StringBuilder();
    sb.append("<html>");
    sb.append("<head>");
    sb.append("<title>Example SSO Widget</title>");
    sb.append("</head>");
    sb.append("<body>").append(endl);
    sb.append("<h2 align=\"center\">Example SSO Widget").append(" Protected Page on ").append(request.getServerName()).append("</h2>").append(endl);
    sb.append(new java.util.Date()).append("<br/><br/>").append(endl);
    sb.append("request.getRemoteUser() = ");
    if (request.getRemoteUser() != null) {
        sb.append(request.getRemoteUser()).append("<br/>").append(endl);
    } else {
        sb.append("None").append("<br/>").append(endl);
    }
    sb.append("request.getUserPrincipal() = ");
    Principal p = request.getUserPrincipal();
    if (p != null) {
        sb.append(p.getName()).append("<br/><br/>").append(endl);
    } else {
        sb.append("None").append("<br/><br/>").append(endl);
    }
    if (request.getContextPath() != null && !"".equals(request.getContextPath())) {
        sb.append("</p><p>").append(endl);
        sb.append("The context root name of this application is ").append(request.getContextPath()).append(endl);
        sb.append("</p>").append(endl);
    }
    sb.append("<h3>Released Attributes:</h3>").append(endl);
    Map attributes = null;
    if (p != null) {
        AttributePrincipal principal = (AttributePrincipal) p;
        attributes = principal.getAttributes();
        if (attributes != null && attributes.size() > 0) {
            Iterator iterator = attributes.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                Object value = entry.getValue();
                if (value instanceof String) {
                    sb.append(entry.getKey()).append(": ").append(value).append("<br/>").append(endl);
                } else if (value instanceof List) {
                    sb.append(entry.getKey()).append(" is a List:<br/>").append(endl);
                    for (Object o : ((List) value)) {
                        sb.append("&nbsp;&nbsp;&nbsp;").append(o.toString()).append("<br/>").append(endl);
                    }
                }
            }
        }
    } else {
        sb.append("None").append(endl);
    }
    sb.append("<h3>Cookies:</h3>").append(endl);
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        sb.append("getCookies() = <br/>").append(endl);
        for (Cookie o : cookies) {
            sb.append("&nbsp;&nbsp;&nbsp;").append(o.getName()).append(": ").append(o.getValue()).append("<br/>").append(endl);
        }
    } else {
        sb.append("getCookies() = null<br/>").append(endl);
    }
    sb.append("<h3>Headers:</h3>").append(endl);
    Enumeration<String> hdrEnum = request.getHeaderNames();
    if (hdrEnum != null) {
        sb.append("getHeaders() = <br/>").append(endl);
        while (hdrEnum.hasMoreElements()) {
            String name = (String) hdrEnum.nextElement();
            sb.append("&nbsp;&nbsp;&nbsp;").append(name).append(": ").append(request.getHeader(name)).append("<br/>").append(endl);
        }
    } else {
        sb.append("getHeaderNames() = null<br/>").append(endl);
    }
    // <input type="hidden" name="LogoutType" value="AppicationLogout">
    //        sb.append( "<br/><br/>" ).append( endl );
    //        sb.append( "<form name=\"Logout\" action=\"LogoutServlet\" method=\"get\">" );
    //        sb.append( "<input type=\"hidden\" name=\"LogoutType\" value=\"ApplicationLogout\"/>" ).append( endl );
    //        sb.append( "<input type=\"submit\" value=\"Logout\"/></form><br/>" ).append( endl );
    //        sb.append( "<form name=\"SSOLogout\" action=\"LogoutServlet\" method=\"get\">" );
    //        sb.append( "<input type=\"hidden\" name=\"LogoutType\" value=\"SingleSignOut\"/>" ).append( endl );
    //        sb.append( "<input type=\"submit\" value=\"Single Sign-Out\"/></form><br/>" ).append( endl );
    sb.append("</body></html>").append(endl);
    out.println(sb.toString());
}
Also used : Cookie(javax.servlet.http.Cookie) Iterator(java.util.Iterator) List(java.util.List) Map(java.util.Map) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal) Principal(java.security.Principal) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal)

Example 3 with AttributePrincipal

use of org.jasig.cas.client.authentication.AttributePrincipal in project cas by apereo.

the class AbstractSamlProfileHandlerController method buildCasAssertion.

/**
 * Build  cas assertion.
 *
 * @param authentication      the authentication
 * @param service             the service
 * @param registeredService   the registered service
 * @param attributesToCombine the attributes to combine
 * @return the assertion
 */
protected Assertion buildCasAssertion(final Authentication authentication, final Service service, final RegisteredService registeredService, final Map<String, Object> attributesToCombine) {
    final Map attributes = registeredService.getAttributeReleasePolicy().getAttributes(authentication.getPrincipal(), service, registeredService);
    final AttributePrincipal principal = new AttributePrincipalImpl(authentication.getPrincipal().getId(), attributes);
    final Map authnAttrs = new LinkedHashMap(authentication.getAttributes());
    authnAttrs.putAll(attributesToCombine);
    return new AssertionImpl(principal, DateTimeUtils.dateOf(authentication.getAuthenticationDate()), null, DateTimeUtils.dateOf(authentication.getAuthenticationDate()), authnAttrs);
}
Also used : AssertionImpl(org.jasig.cas.client.validation.AssertionImpl) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal) AttributePrincipalImpl(org.jasig.cas.client.authentication.AttributePrincipalImpl) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with AttributePrincipal

use of org.jasig.cas.client.authentication.AttributePrincipal in project pwm by pwm-project.

the class CASFilterAuthenticationProvider method authUserUsingCASClearPass.

private static boolean authUserUsingCASClearPass(final PwmRequest pwmRequest) throws UnsupportedEncodingException, PwmUnrecoverableException, ChaiUnavailableException, PwmOperationalException {
    final PwmSession pwmSession = pwmRequest.getPwmSession();
    final PwmApplication pwmApplication = pwmRequest.getPwmApplication();
    final HttpSession session = pwmRequest.getHttpServletRequest().getSession();
    // make sure user session isn't already authenticated
    if (pwmSession.isAuthenticated()) {
        return false;
    }
    // read CAS assertion out of the header (if it exists);
    final Assertion assertion = (Assertion) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
    if (assertion == null) {
        LOGGER.trace(pwmSession, "no CAS assertion header present, skipping CAS authentication attempt");
        return false;
    }
    final String username = assertion.getPrincipal().getName();
    PasswordData password = null;
    final AttributePrincipal attributePrincipal = assertion.getPrincipal();
    final Map<String, Object> casAttributes = attributePrincipal.getAttributes();
    final String encodedPsw = (String) casAttributes.get("credential");
    if (encodedPsw == null) {
        LOGGER.trace("No credential");
    } else {
        final Map<FileInformation, FileContent> privatekey = pwmRequest.getConfig().readSettingAsFile(PwmSetting.CAS_CLEARPASS_KEY);
        final String alg = pwmRequest.getConfig().readSettingAsString(PwmSetting.CAS_CLEARPASS_ALGORITHM);
        password = decryptPassword(alg, privatekey, encodedPsw);
    }
    // If using the old method
    final String clearPassUrl = pwmRequest.getConfig().readSettingAsString(PwmSetting.CAS_CLEAR_PASS_URL);
    if ((clearPassUrl != null && clearPassUrl.length() > 0) && (password == null || password.getStringValue().length() < 1)) {
        LOGGER.trace(pwmSession, "Using CAS clearpass via proxy");
        // read cas proxy ticket
        final String proxyTicket = assertion.getPrincipal().getProxyTicketFor(clearPassUrl);
        if (proxyTicket == null) {
            LOGGER.trace(pwmSession, "no CAS proxy ticket available, skipping CAS authentication attempt");
            return false;
        }
        final String clearPassRequestUrl = clearPassUrl + "?" + "ticket=" + proxyTicket + "&" + "service=" + StringUtil.urlEncode(clearPassUrl);
        try {
            final String response = CommonUtils.getResponseFromServer(new URL(clearPassRequestUrl), new HttpsURLConnectionFactory(), "UTF-8");
            password = new PasswordData(XmlUtils.getTextForElement(response, "credentials"));
        } catch (MalformedURLException e) {
            LOGGER.error(pwmSession, "Invalid CAS clearPassUrl");
        }
    }
    if (password == null || password.getStringValue().length() < 1) {
        final String errorMsg = "CAS server did not return credentials for user '" + username + "'";
        LOGGER.trace(pwmSession, errorMsg);
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_WRONGPASSWORD, errorMsg);
        throw new PwmOperationalException(errorInformation);
    }
    // user isn't already authenticated and has CAS assertion and password, so try to auth them.
    LOGGER.debug(pwmSession, "attempting to authenticate user '" + username + "' using CAS assertion and password");
    final SessionAuthenticator sessionAuthenticator = new SessionAuthenticator(pwmApplication, pwmSession, PwmAuthenticationSource.CAS);
    sessionAuthenticator.searchAndAuthenticateUser(username, password, null, null);
    return true;
}
Also used : PwmApplication(password.pwm.PwmApplication) MalformedURLException(java.net.MalformedURLException) FileInformation(password.pwm.config.value.FileValue.FileInformation) SessionAuthenticator(password.pwm.ldap.auth.SessionAuthenticator) HttpSession(javax.servlet.http.HttpSession) Assertion(org.jasig.cas.client.validation.Assertion) URL(java.net.URL) PwmOperationalException(password.pwm.error.PwmOperationalException) FileContent(password.pwm.config.value.FileValue.FileContent) HttpsURLConnectionFactory(org.jasig.cas.client.ssl.HttpsURLConnectionFactory) ErrorInformation(password.pwm.error.ErrorInformation) PwmSession(password.pwm.http.PwmSession) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal)

Example 5 with AttributePrincipal

use of org.jasig.cas.client.authentication.AttributePrincipal in project pac4j by pac4j.

the class CasAuthenticator method validate.

@Override
public void validate(final TokenCredentials credentials, final WebContext context) {
    init();
    final String ticket = credentials.getToken();
    try {
        final String finalCallbackUrl = callbackUrlResolver.compute(urlResolver, callbackUrl, clientName, context);
        final Assertion assertion = configuration.retrieveTicketValidator(context).validate(ticket, finalCallbackUrl);
        final AttributePrincipal principal = assertion.getPrincipal();
        logger.debug("principal: {}", principal);
        final String id = principal.getName();
        final Map<String, Object> newPrincipalAttributes = new HashMap<>();
        final Map<String, Object> newAuthenticationAttributes = new HashMap<>();
        // restore both sets of attributes
        final Map<String, Object> oldPrincipalAttributes = principal.getAttributes();
        final Map<String, Object> oldAuthenticationAttributes = assertion.getAttributes();
        final InternalAttributeHandler attrHandler = ProfileHelper.getInternalAttributeHandler();
        if (oldPrincipalAttributes != null) {
            oldPrincipalAttributes.entrySet().stream().forEach(e -> newPrincipalAttributes.put(e.getKey(), attrHandler.restore(e.getValue())));
        }
        if (oldAuthenticationAttributes != null) {
            oldAuthenticationAttributes.entrySet().stream().forEach(e -> newAuthenticationAttributes.put(e.getKey(), attrHandler.restore(e.getValue())));
        }
        final CommonProfile profile;
        // in case of CAS proxy, don't restore the profile, just build a CAS one
        if (configuration.getProxyReceptor() != null) {
            profile = getProfileDefinition().newProfile(principal, configuration.getProxyReceptor());
            profile.setId(ProfileHelper.sanitizeIdentifier(profile, id));
            getProfileDefinition().convertAndAdd(profile, newPrincipalAttributes, newAuthenticationAttributes);
        } else {
            profile = ProfileHelper.restoreOrBuildProfile(getProfileDefinition(), id, newPrincipalAttributes, newAuthenticationAttributes, principal, configuration.getProxyReceptor());
        }
        logger.debug("profile returned by CAS: {}", profile);
        credentials.setUserProfile(profile);
    } catch (final TicketValidationException e) {
        String message = "cannot validate CAS ticket: " + ticket;
        throw new TechnicalException(message, e);
    }
}
Also used : TechnicalException(org.pac4j.core.exception.TechnicalException) InternalAttributeHandler(org.pac4j.core.profile.InternalAttributeHandler) HashMap(java.util.HashMap) CommonProfile(org.pac4j.core.profile.CommonProfile) Assertion(org.jasig.cas.client.validation.Assertion) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal) TicketValidationException(org.jasig.cas.client.validation.TicketValidationException)

Aggregations

AttributePrincipal (org.jasig.cas.client.authentication.AttributePrincipal)19 Assertion (org.jasig.cas.client.validation.Assertion)9 HashMap (java.util.HashMap)4 AttributePrincipalImpl (org.jasig.cas.client.authentication.AttributePrincipalImpl)4 AssertionImpl (org.jasig.cas.client.validation.AssertionImpl)4 Test (org.junit.Test)4 Map (java.util.Map)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 TicketValidationException (org.jasig.cas.client.validation.TicketValidationException)3 Principal (java.security.Principal)2 HttpSession (javax.servlet.http.HttpSession)2 Ignore (org.junit.Ignore)2 TechnicalException (org.pac4j.core.exception.TechnicalException)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 ParseException (com.vividsolutions.jts.io.ParseException)1 SecurityServiceException (ddf.security.service.SecurityServiceException)1 STSClientConfiguration (ddf.security.sts.client.configuration.STSClientConfiguration)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1 Iterator (java.util.Iterator)1