Search in sources :

Example 6 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class DefaultAcceptableUsagePolicyRepository method verify.

@Override
public Pair<Boolean, Principal> verify(final RequestContext requestContext, final Credential credential) {
    final String key = credential.getId();
    final Principal principal = WebUtils.getPrincipalFromRequestContext(requestContext, this.ticketRegistrySupport);
    if (this.policyMap.containsKey(key)) {
        return Pair.of(this.policyMap.get(key), principal);
    }
    return Pair.of(false, principal);
}
Also used : Principal(org.apereo.cas.authentication.principal.Principal)

Example 7 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class BaseOAuthWrapperController method createAuthentication.

/**
     * Create an authentication from a user profile.
     *
     * @param profile           the given user profile
     * @param registeredService the registered service
     * @param context           the context
     * @param service           the service
     * @return the built authentication
     */
protected Authentication createAuthentication(final UserProfile profile, final RegisteredService registeredService, final J2EContext context, final Service service) {
    final Principal newPrincipal = this.scopeToAttributesFilter.filter(service, this.principalFactory.createPrincipal(profile.getId(), profile.getAttributes()), registeredService, context);
    LOGGER.debug("Created final principal [{}] after filtering attributes based on [{}]", newPrincipal, registeredService);
    final String authenticator = profile.getClass().getCanonicalName();
    final CredentialMetaData metadata = new BasicCredentialMetaData(new BasicIdentifiableCredential(profile.getId()));
    final HandlerResult handlerResult = new DefaultHandlerResult(authenticator, metadata, newPrincipal, new ArrayList<>());
    final String state = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.STATE), StringUtils.EMPTY);
    final String nonce = StringUtils.defaultIfBlank(context.getRequestParameter(OAuthConstants.NONCE), StringUtils.EMPTY);
    LOGGER.debug("OAuth [{}] is [{}], and [{}] is [{}]", OAuthConstants.STATE, state, OAuthConstants.NONCE, nonce);
    final AuthenticationBuilder bldr = DefaultAuthenticationBuilder.newInstance().addAttribute("permissions", profile.getPermissions()).addAttribute("roles", profile.getRoles()).addAttribute(OAuthConstants.STATE, state).addAttribute(OAuthConstants.NONCE, nonce).addCredential(metadata).setPrincipal(newPrincipal).setAuthenticationDate(ZonedDateTime.now()).addSuccess(profile.getClass().getCanonicalName(), handlerResult);
    // Add "other" profile attributes as authentication attributes.
    if (casProperties.getAuthn().getOauth().getAccessToken().isReleaseProtocolAttributes()) {
        profile.getAttributes().forEach((k, v) -> {
            if (!newPrincipal.getAttributes().containsKey(k)) {
                LOGGER.debug("Added attribute [{}] with value [{}] to the authentication", k, v);
                bldr.addAttribute(k, v);
            } else {
                LOGGER.debug("Skipped over attribute [{}] since it's already contained by the principal", k);
            }
        });
    }
    return bldr.build();
}
Also used : DefaultAuthenticationBuilder(org.apereo.cas.authentication.DefaultAuthenticationBuilder) AuthenticationBuilder(org.apereo.cas.authentication.AuthenticationBuilder) BasicIdentifiableCredential(org.apereo.cas.authentication.BasicIdentifiableCredential) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) HandlerResult(org.apereo.cas.authentication.HandlerResult) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData) CredentialMetaData(org.apereo.cas.authentication.CredentialMetaData) DefaultHandlerResult(org.apereo.cas.authentication.DefaultHandlerResult) Principal(org.apereo.cas.authentication.principal.Principal) BasicCredentialMetaData(org.apereo.cas.authentication.BasicCredentialMetaData)

Example 8 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class Cas30JsonResponseView method createAuthenticationSuccess.

private CasServiceResponseAuthenticationSuccess createAuthenticationSuccess(final Map<String, Object> model) {
    final CasServiceResponseAuthenticationSuccess success = new CasServiceResponseAuthenticationSuccess();
    success.setAttributes(getModelAttributes(model));
    final Principal principal = getPrincipal(model);
    success.setUser(principal.getId());
    success.setProxyGrantingTicket(getProxyGrantingTicketIou(model));
    final Collection<Authentication> chainedAuthentications = getChainedAuthentications(model);
    if (chainedAuthentications != null && !chainedAuthentications.isEmpty()) {
        final List<String> proxies = chainedAuthentications.stream().map(authn -> authn.getPrincipal().getId()).collect(Collectors.toList());
        success.setProxies(proxies);
    }
    return success;
}
Also used : Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ProtocolAttributeEncoder(org.apereo.cas.authentication.ProtocolAttributeEncoder) HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) MappingJackson2JsonView(org.springframework.web.servlet.view.json.MappingJackson2JsonView) Authentication(org.apereo.cas.authentication.Authentication) Map(java.util.Map) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) Principal(org.apereo.cas.authentication.principal.Principal) ServicesManager(org.apereo.cas.services.ServicesManager) Authentication(org.apereo.cas.authentication.Authentication) Principal(org.apereo.cas.authentication.principal.Principal)

Example 9 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class OAuthUserAuthenticator method validate.

@Override
public void validate(final UsernamePasswordCredentials credentials, final WebContext context) throws CredentialsException {
    final UsernamePasswordCredential casCredential = new UsernamePasswordCredential(credentials.getUsername(), credentials.getPassword());
    try {
        final String clientId = context.getRequestParameter(OAuthConstants.CLIENT_ID);
        final Service service = this.webApplicationServiceFactory.createService(clientId);
        final RegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(this.servicesManager, clientId);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
        final AuthenticationResult authenticationResult = this.authenticationSystemSupport.handleAndFinalizeSingleAuthenticationTransaction(null, casCredential);
        final Authentication authentication = authenticationResult.getAuthentication();
        final Principal principal = authentication.getPrincipal();
        final OAuthUserProfile profile = new OAuthUserProfile();
        final String id = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service);
        LOGGER.debug("Created profile id [{}]", id);
        profile.setId(id);
        final Map<String, Object> attributes = registeredService.getAttributeReleasePolicy().getAttributes(principal, registeredService);
        profile.addAttributes(attributes);
        LOGGER.debug("Authenticated user profile [{}]", profile);
        credentials.setUserProfile(profile);
    } catch (final Exception e) {
        throw new CredentialsException("Cannot login user using CAS internal authentication", e);
    }
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Authentication(org.apereo.cas.authentication.Authentication) RegisteredService(org.apereo.cas.services.RegisteredService) Service(org.apereo.cas.authentication.principal.Service) CredentialsException(org.pac4j.core.exception.CredentialsException) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) Principal(org.apereo.cas.authentication.principal.Principal) CredentialsException(org.pac4j.core.exception.CredentialsException) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 10 with Principal

use of org.apereo.cas.authentication.principal.Principal in project cas by apereo.

the class OAuth20AccessTokenControllerTests method internalVerifyRefreshTokenOk.

private void internalVerifyRefreshTokenOk(final RegisteredService service, final boolean json) throws Exception {
    final Principal principal = createPrincipal();
    final RefreshToken refreshToken = addRefreshToken(principal, service);
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest(GET, CONTEXT + OAuthConstants.ACCESS_TOKEN_URL);
    mockRequest.setParameter(OAuthConstants.GRANT_TYPE, OAuth20GrantTypes.REFRESH_TOKEN.name().toLowerCase());
    mockRequest.setParameter(OAuthConstants.CLIENT_ID, CLIENT_ID);
    mockRequest.setParameter(OAuthConstants.CLIENT_SECRET, CLIENT_SECRET);
    mockRequest.setParameter(OAuthConstants.REFRESH_TOKEN, refreshToken.getId());
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    requiresAuthenticationInterceptor.preHandle(mockRequest, mockResponse, null);
    oAuth20AccessTokenController.handleRequestInternal(mockRequest, mockResponse);
    //This assert fails because deep down inside Oauth2 access token ctrl the refresh token gets deleted
    //assertNotNull(oAuth20AccessTokenController.getRegistry().getTicket((refreshToken.getId())));
    assertEquals(200, mockResponse.getStatus());
    final String body = mockResponse.getContentAsString();
    final String accessTokenId;
    if (json) {
        assertEquals("application/json", mockResponse.getContentType());
        assertTrue(body.contains('"' + OAuthConstants.ACCESS_TOKEN + "\":\"AT-"));
        assertFalse(body.contains('"' + OAuthConstants.REFRESH_TOKEN + "\":\"RT-"));
        assertTrue(body.contains('"' + OAuthConstants.EXPIRES_IN + "\":7"));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + "\":\"", "\",\"");
    } else {
        assertEquals("text/plain", mockResponse.getContentType());
        assertTrue(body.contains(OAuthConstants.ACCESS_TOKEN + '='));
        assertFalse(body.contains(OAuthConstants.REFRESH_TOKEN + '='));
        assertTrue(body.contains(OAuthConstants.EXPIRES_IN + '='));
        accessTokenId = StringUtils.substringBetween(body, OAuthConstants.ACCESS_TOKEN + '=', "&");
    }
    final AccessToken accessToken = oAuth20AccessTokenController.getTicketRegistry().getTicket(accessTokenId, AccessToken.class);
    assertEquals(principal, accessToken.getAuthentication().getPrincipal());
    final int timeLeft = getTimeLeft(body, false, json);
    assertTrue(timeLeft >= TIMEOUT - 10 - DELTA);
}
Also used : RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) Principal(org.apereo.cas.authentication.principal.Principal) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse)

Aggregations

Principal (org.apereo.cas.authentication.principal.Principal)114 HashMap (java.util.HashMap)33 RegisteredService (org.apereo.cas.services.RegisteredService)31 Test (org.junit.Test)29 Authentication (org.apereo.cas.authentication.Authentication)26 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)26 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)26 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)25 Map (java.util.Map)23 Slf4j (lombok.extern.slf4j.Slf4j)23 lombok.val (lombok.val)19 List (java.util.List)15 StringUtils (org.apache.commons.lang3.StringUtils)15 OAuthCode (org.apereo.cas.ticket.code.OAuthCode)15 CollectionUtils (org.apereo.cas.util.CollectionUtils)15 ArrayList (java.util.ArrayList)14 Optional (java.util.Optional)14 Service (org.apereo.cas.authentication.principal.Service)14 Collection (java.util.Collection)11 Collectors (java.util.stream.Collectors)10