org.jasig.cas.client.authentication.AttributePrincipal Java Examples

The following examples show how to use org.jasig.cas.client.authentication.AttributePrincipal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CasAuthenticationHandler.java    From esigate with Apache License 2.0 6 votes vote down vote up
private void addCasAuthentication(OutgoingRequest outgoingRequest, IncomingRequest incomingRequest) {
    String location = outgoingRequest.getRequestLine().getUri();
    String resultLocation = location;
    AttributePrincipal principal = getCasAuthentication(incomingRequest);
    if (principal != null) {
        LOG.debug("User logged in CAS as: " + principal.getName());
        String casProxyTicket = principal.getProxyTicketFor(resultLocation);
        LOG.debug("Proxy ticket retrieved: " + principal.getName() + " for service: " + location + " : "
                + casProxyTicket);
        if (casProxyTicket != null) {
            if (resultLocation.indexOf("?") > 0) {
                resultLocation = resultLocation + "&ticket=" + casProxyTicket;
            } else {
                resultLocation = resultLocation + "?ticket=" + casProxyTicket;
            }
        }
    }
    outgoingRequest.setUri(resultLocation);
}
 
Example #2
Source File: CasUserDetailsService.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
protected ManagedUser parseUserDetails(Assertion assertion) {
    AttributePrincipal principal = assertion.getPrincipal();
    List<GrantedAuthority> grantedAuthorities = Stream.of(defaultAuthorities)
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    return new ManagedUser(principal.getName(), NON_EXISTENT_PASSWORD_VALUE, true, grantedAuthorities);
}
 
Example #3
Source File: MCRCASServlet.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public void doGetPost(MCRServletJob job) throws Exception {
    HttpServletRequest req = job.getRequest();
    HttpServletResponse res = job.getResponse();

    String ticket = req.getParameter("ticket");
    if ((ticket == null) || (ticket.trim().length() == 0)) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // Validate ticket at CAS server
    Cas20ProxyTicketValidator sv = new Cas20ProxyTicketValidator(serverURL);
    sv.setAcceptAnyProxy(true);
    Assertion a = sv.validate(ticket, clientURL);
    AttributePrincipal principal = a.getPrincipal();

    // Get user name logged in
    String userName = principal.getName();
    LOGGER.info("Login {}", userName);

    MCRUser user;
    boolean userExists = MCRUserManager.exists(userName, realmID);
    if (userExists) {
        user = MCRUserManager.getUser(userName, realmID);
    } else {
        user = new MCRUser(userName, realmID);
    }

    // Get user properties from LDAP server
    boolean userChanged = MCRLDAPClient.instance().updateUserProperties(user);
    if (userChanged && userExists) {
        MCRUserManager.updateUser(user);
    }

    // Store login user in session and redirect browser to target url
    MCRSessionMgr.getCurrentSession().setUserInformation(user);
    // MCR-1154
    req.changeSessionId();
    MCRLoginServlet.redirect(res);
}
 
Example #4
Source File: AuthenticatedNameTranslator.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response,
                          final Assertion assertion, final String authenticationKey) {
    if (assertion == null || assertion.getPrincipal() == null) {
        logger.error("No valid assertion or principal could be found to translate");
        return;
    }
    final AttributePrincipal casPrincipal = assertion.getPrincipal();
    logger.debug("principalName found and being passed on: {}", casPrincipal.getName());

    // Pass authenticated principal back to IdP to finish its part of authentication request processing
    final Collection<IdPAttributePrincipal> assertionAttributes = produceIdpAttributePrincipal(assertion.getAttributes());
    final Collection<IdPAttributePrincipal> principalAttributes = produceIdpAttributePrincipal(casPrincipal.getAttributes());

    if (!assertionAttributes.isEmpty() || !principalAttributes.isEmpty()) {
        logger.debug("Found attributes from CAS. Processing...");
        final Set<Principal> principals = new HashSet<>();

        principals.addAll(assertionAttributes);
        principals.addAll(principalAttributes);
        principals.add(new UsernamePrincipal(casPrincipal.getName()));

        request.setAttribute(ExternalAuthentication.SUBJECT_KEY, new Subject(false, principals,
            Collections.emptySet(), Collections.emptySet()));
        logger.info("Created an IdP subject instance with principals containing attributes for {} ", casPrincipal.getName());

    } else {
        logger.debug("No attributes released from CAS. Creating an IdP principal for {}", casPrincipal.getName());
        request.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, casPrincipal.getName());
    }
}
 
Example #5
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
private Assertion createMockAssertion() {
    final Assertion assertion = Mockito.mock(Assertion.class);
    final AttributePrincipal attributePrincipal = Mockito.mock(AttributePrincipal.class);

    BDDMockito.given(attributePrincipal.getName()).willReturn(JDOE);
    BDDMockito.given(assertion.getPrincipal()).willReturn(attributePrincipal);

    return assertion;
}
 
Example #6
Source File: CasUserDetailsService.java    From kylin with Apache License 2.0 5 votes vote down vote up
protected ManagedUser parseUserDetails(Assertion assertion) {
    AttributePrincipal principal = assertion.getPrincipal();
    List<GrantedAuthority> grantedAuthorities = Stream.of(defaultAuthorities)
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    return new ManagedUser(principal.getName(), NON_EXISTENT_PASSWORD_VALUE, true, grantedAuthorities);
}
 
Example #7
Source File: AuthenticatedNameTranslator.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
@Override
public void doTranslation(final HttpServletRequest request, final HttpServletResponse response,
                          final Assertion assertion, final String authenticationKey) {
    if (assertion == null || assertion.getPrincipal() == null) {
        logger.error("No valid assertion or principal could be found to translate");
        return;
    }
    final AttributePrincipal casPrincipal = assertion.getPrincipal();
    logger.debug("principalName found and being passed on: {}", casPrincipal.getName());

    // Pass authenticated principal back to IdP to finish its part of authentication request processing
    final Collection<IdPAttributePrincipal> assertionAttributes = produceIdpAttributePrincipal(assertion.getAttributes());
    final Collection<IdPAttributePrincipal> principalAttributes = produceIdpAttributePrincipal(casPrincipal.getAttributes());

    if (!assertionAttributes.isEmpty() || !principalAttributes.isEmpty()) {
        logger.debug("Found attributes from CAS. Processing...");
        final Set<Principal> principals = new HashSet<>();

        principals.addAll(assertionAttributes);
        principals.addAll(principalAttributes);
        principals.add(new UsernamePrincipal(casPrincipal.getName()));

        request.setAttribute(ExternalAuthentication.SUBJECT_KEY, new Subject(false, principals,
            Collections.emptySet(), Collections.emptySet()));
        logger.info("Created an IdP subject instance with principals containing attributes for {} ", casPrincipal.getName());

    } else {
        logger.debug("No attributes released from CAS. Creating an IdP principal for {}", casPrincipal.getName());
        request.setAttribute(ExternalAuthentication.PRINCIPAL_NAME_KEY, casPrincipal.getName());
    }
}
 
Example #8
Source File: ShibcasAuthServletTest.java    From shib-cas-authn3 with Apache License 2.0 5 votes vote down vote up
private Assertion createMockAssertion() {
    final Assertion assertion = Mockito.mock(Assertion.class);
    final AttributePrincipal attributePrincipal = Mockito.mock(AttributePrincipal.class);

    BDDMockito.given(attributePrincipal.getName()).willReturn(JDOE);
    BDDMockito.given(assertion.getPrincipal()).willReturn(attributePrincipal);

    return assertion;
}
 
Example #9
Source File: CasAuthenticationHandler.java    From esigate with Apache License 2.0 5 votes vote down vote up
private AttributePrincipal getCasAuthentication(IncomingRequest incomingRequest) {
    Principal principal = incomingRequest.getUserPrincipal();
    if (principal != null && principal instanceof AttributePrincipal) {
        return (AttributePrincipal) principal;
    }
    return null;
}
 
Example #10
Source File: CasAuthenticationHandlerTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
public void testCasAuthenticationOk() throws Exception {
    AttributePrincipal userPrincipal = new AttributePrincipal() {
        private static final long serialVersionUID = 1L;

        @Override
        public Map<String, Object> getAttributes() {
            return null;
        }

        @Override
        public String getName() {
            return "test";
        }

        @Override
        public String getProxyTicketFor(String arg0) {
            return "proxy_ticket";
        }
    };
    IncomingRequest incomingRequest = TestUtils.createIncomingRequest().setUserPrincipal(userPrincipal).build();
    DriverRequest driverRequest = new DriverRequest(incomingRequest, driver1, "/");
    OutgoingRequest outgoingRequest =
            httpClientRequestExecutor.createOutgoingRequest(driverRequest, "http://localhost:8080", true);
    FragmentEvent event =
            new FragmentEvent(driverRequest.getOriginalRequest(), outgoingRequest, outgoingRequest.getContext());
    CloseableHttpResponse httpResponse = BasicCloseableHttpResponse.adapt(createMockResponse("0"));
    httpResponse.setHeader("Location", "http://localhost/loginurl?service=http");
    event.setHttpResponse(httpResponse);

    HttpResponse responseOnceAuthenticated = createMockResponse("1");
    mockConnectionManager.setResponse(responseOnceAuthenticated);

    handler.event(EventManager.EVENT_FRAGMENT_POST, event);

    // A new request should have been sent with the proxy ticket
    assertNotNull(mockConnectionManager.getSentRequest());
    assertEquals("/?ticket=proxy_ticket", mockConnectionManager.getSentRequest().getRequestLine().getUri());
    assertEquals(200, event.getHttpResponse().getStatusLine().getStatusCode());
    assertEquals("1", EntityUtils.toString(event.getHttpResponse().getEntity()));
}
 
Example #11
Source File: TicketValidationService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Validates and parses the given ID ticket, returning a map of all
 * available tokens for the given user based on attributes provided by the
 * CAS server.  If the ticket is invalid an exception is thrown.
 *
 * @param ticket
 *     The ID ticket to validate and parse.
 *
 * @param credentials
 *     The Credentials object to store retrieved username and
 *     password values in.
 *
 * @return
 *     A Map all of tokens for the user parsed from attributes returned
 *     by the CAS server.
 *
 * @throws GuacamoleException
 *     If the ID ticket is not valid or guacamole.properties could
 *     not be parsed.
 */
public Map<String, String> validateTicket(String ticket,
        Credentials credentials) throws GuacamoleException {

    // Retrieve the configured CAS URL, establish a ticket validator,
    // and then attempt to validate the supplied ticket.  If that succeeds,
    // grab the principal returned by the validator.
    URI casServerUrl = confService.getAuthorizationEndpoint();
    Cas20ProxyTicketValidator validator = new Cas20ProxyTicketValidator(casServerUrl.toString());
    validator.setAcceptAnyProxy(true);
    validator.setEncoding("UTF-8");
    try {
        Map<String, String> tokens = new HashMap<>();
        URI confRedirectURI = confService.getRedirectURI();
        Assertion a = validator.validate(ticket, confRedirectURI.toString());
        AttributePrincipal principal =  a.getPrincipal();
        Map<String, Object> ticketAttrs =
                new HashMap<>(principal.getAttributes());

        // Retrieve username and set the credentials.
        String username = principal.getName();
        if (username == null)
            throw new GuacamoleSecurityException("No username provided by CAS.");
        
        credentials.setUsername(username);

        // Retrieve password, attempt decryption, and set credentials.
        Object credObj = ticketAttrs.remove("credential");
        if (credObj != null) {
            String clearPass = decryptPassword(credObj.toString());
            if (clearPass != null && !clearPass.isEmpty())
                credentials.setPassword(clearPass);
        }
        
        // Convert remaining attributes that have values to Strings
        for (Entry <String, Object> attr : ticketAttrs.entrySet()) {
            String tokenName = TokenName.canonicalize(attr.getKey(),
                    CAS_ATTRIBUTE_TOKEN_PREFIX);
            Object value = attr.getValue();
            if (value != null)
                tokens.put(tokenName, value.toString());
        }

        return tokens;

    } 
    catch (TicketValidationException e) {
        throw new GuacamoleException("Ticket validation failed.", e);
    }

}
 
Example #12
Source File: TicketValidationService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Validates and parses the given ID ticket, returning a map of all
 * available tokens for the given user based on attributes provided by the
 * CAS server.  If the ticket is invalid an exception is thrown.
 *
 * @param ticket
 *     The ID ticket to validate and parse.
 *
 * @param credentials
 *     The Credentials object to store retrieved username and
 *     password values in.
 *
 * @return
 *     A Map all of tokens for the user parsed from attributes returned
 *     by the CAS server.
 *
 * @throws GuacamoleException
 *     If the ID ticket is not valid or guacamole.properties could
 *     not be parsed.
 */
public Map<String, String> validateTicket(String ticket,
        Credentials credentials) throws GuacamoleException {

    // Retrieve the configured CAS URL, establish a ticket validator,
    // and then attempt to validate the supplied ticket.  If that succeeds,
    // grab the principal returned by the validator.
    URI casServerUrl = confService.getAuthorizationEndpoint();
    Cas20ProxyTicketValidator validator = new Cas20ProxyTicketValidator(casServerUrl.toString());
    validator.setAcceptAnyProxy(true);
    validator.setEncoding("UTF-8");
    try {
        Map<String, String> tokens = new HashMap<>();
        URI confRedirectURI = confService.getRedirectURI();
        Assertion a = validator.validate(ticket, confRedirectURI.toString());
        AttributePrincipal principal =  a.getPrincipal();
        Map<String, Object> ticketAttrs =
                new HashMap<>(principal.getAttributes());

        // Retrieve username and set the credentials.
        String username = principal.getName();
        if (username == null)
            throw new GuacamoleSecurityException("No username provided by CAS.");
        
        credentials.setUsername(username);

        // Retrieve password, attempt decryption, and set credentials.
        Object credObj = ticketAttrs.remove("credential");
        if (credObj != null) {
            String clearPass = decryptPassword(credObj.toString());
            if (clearPass != null && !clearPass.isEmpty())
                credentials.setPassword(clearPass);
        }
        
        // Convert remaining attributes that have values to Strings
        for (Entry <String, Object> attr : ticketAttrs.entrySet()) {
            String tokenName = TokenName.canonicalize(attr.getKey(),
                    CAS_ATTRIBUTE_TOKEN_PREFIX);
            Object value = attr.getValue();
            if (value != null)
                tokens.put(tokenName, value.toString());
        }

        return tokens;

    } 
    catch (TicketValidationException e) {
        throw new GuacamoleException("Ticket validation failed.", e);
    }

}