Search in sources :

Example 1 with UserProfile

use of org.pac4j.core.profile.UserProfile in project cas by apereo.

the class AbstractWrapperAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    CommonHelper.assertNotNull("profileCreator", this.profileCreator);
    final C credentials = convertToPac4jCredentials((I) credential);
    LOGGER.debug("credentials: [{}]", credentials);
    try {
        final Authenticator authenticator = getAuthenticator(credential);
        if (authenticator instanceof InitializableObject) {
            ((InitializableObject) authenticator).init();
        }
        if (authenticator instanceof InitializableWebObject) {
            ((InitializableWebObject) authenticator).init(getWebContext());
        }
        CommonHelper.assertNotNull("authenticator", authenticator);
        authenticator.validate(credentials, getWebContext());
        final UserProfile profile = this.profileCreator.create(credentials, getWebContext());
        LOGGER.debug("profile: [{}]", profile);
        return createResult(new ClientCredential(credentials), profile);
    } catch (final Exception e) {
        LOGGER.error("Failed to validate credentials", e);
        throw new FailedLoginException("Failed to validate credentials: " + e.getMessage());
    }
}
Also used : ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) FailedLoginException(javax.security.auth.login.FailedLoginException) UserProfile(org.pac4j.core.profile.UserProfile) InitializableObject(org.pac4j.core.util.InitializableObject) Authenticator(org.pac4j.core.credentials.authenticator.Authenticator) InitializableWebObject(org.pac4j.core.util.InitializableWebObject) GeneralSecurityException(java.security.GeneralSecurityException) FailedLoginException(javax.security.auth.login.FailedLoginException) PreventedException(org.apereo.cas.authentication.PreventedException)

Example 2 with UserProfile

use of org.pac4j.core.profile.UserProfile in project cas by apereo.

the class ClientAuthenticationHandler method doAuthentication.

@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    try {
        final ClientCredential clientCredentials = (ClientCredential) credential;
        LOGGER.debug("clientCredentials  [{}]", clientCredentials);
        final Credentials credentials = clientCredentials.getCredentials();
        final String clientName = credentials.getClientName();
        LOGGER.debug("clientName:  [{}]", clientName);
        // get client
        final Client client = this.clients.findClient(clientName);
        LOGGER.debug("client: [{}]", client);
        // web context
        final HttpServletRequest request = WebUtils.getHttpServletRequest();
        final HttpServletResponse response = WebUtils.getHttpServletResponse();
        final WebContext webContext = WebUtils.getPac4jJ2EContext(request, response);
        // get user profile
        final UserProfile userProfile = client.getUserProfile(credentials, webContext);
        LOGGER.debug("userProfile: [{}]", userProfile);
        return createResult(clientCredentials, userProfile);
    } catch (final HttpAction e) {
        throw new PreventedException(e);
    }
}
Also used : ClientCredential(org.apereo.cas.authentication.principal.ClientCredential) HttpServletRequest(javax.servlet.http.HttpServletRequest) WebContext(org.pac4j.core.context.WebContext) UserProfile(org.pac4j.core.profile.UserProfile) HttpServletResponse(javax.servlet.http.HttpServletResponse) PreventedException(org.apereo.cas.authentication.PreventedException) Client(org.pac4j.core.client.Client) Credentials(org.pac4j.core.credentials.Credentials) HttpAction(org.pac4j.core.exception.HttpAction)

Example 3 with UserProfile

use of org.pac4j.core.profile.UserProfile in project cas by apereo.

the class OAuth20AccessTokenEndpointController method handleRequestInternal.

/**
     * Handle request internal model and view.
     *
     * @param request  the request
     * @param response the response
     * @return the model and view
     * @throws Exception the exception
     */
@PostMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.ACCESS_TOKEN_URL)
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    try {
        response.setContentType(MediaType.TEXT_PLAIN_VALUE);
        if (!verifyAccessTokenRequest(request, response)) {
            LOGGER.error("Access token request verification fails");
            return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_REQUEST);
        }
        final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
        final Service service;
        final Authentication authentication;
        final boolean generateRefreshToken;
        final OAuthRegisteredService registeredService;
        final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
        final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
        if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE) || isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
            final Optional<UserProfile> profile = manager.get(true);
            final String clientId = profile.get().getId();
            registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
            // we generate a refresh token if requested by the service but not from a refresh token
            generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken() && isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE);
            final String parameterName;
            if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
                parameterName = OAuthConstants.CODE;
            } else {
                parameterName = OAuthConstants.REFRESH_TOKEN;
            }
            final OAuthToken token = getToken(request, parameterName);
            if (token == null) {
                LOGGER.error("No token found for authorization_code or refresh_token grant types");
                return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
            }
            service = token.getService();
            authentication = token.getAuthentication();
        } else {
            final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
            registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
            generateRefreshToken = registeredService != null && registeredService.isGenerateRefreshToken();
            try {
                // resource owner password grant type
                final Optional<OAuthUserProfile> profile = manager.get(true);
                if (!profile.isPresent()) {
                    throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
                }
                service = createService(registeredService, context);
                authentication = createAuthentication(profile.get(), registeredService, context, service);
                RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication);
            } catch (final Exception e) {
                LOGGER.error(e.getMessage(), e);
                return OAuthUtils.writeTextError(response, OAuthConstants.INVALID_GRANT);
            }
        }
        final AccessToken accessToken = generateAccessToken(service, authentication, context);
        RefreshToken refreshToken = null;
        if (generateRefreshToken) {
            refreshToken = this.refreshTokenFactory.create(service, authentication);
            getTicketRegistry().addTicket(refreshToken);
        }
        LOGGER.debug("access token: [{}] / timeout: [{}] / refresh token: [{}]", accessToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), refreshToken);
        final String responseType = context.getRequestParameter(OAuthConstants.RESPONSE_TYPE);
        final OAuth20ResponseTypes type = Arrays.stream(OAuth20ResponseTypes.values()).filter(t -> t.getType().equalsIgnoreCase(responseType)).findFirst().orElse(OAuth20ResponseTypes.CODE);
        this.accessTokenResponseGenerator.generate(request, response, registeredService, service, accessToken, refreshToken, casProperties.getTicket().getTgt().getTimeToKillInSeconds(), type);
        getTicketRegistry().addTicket(accessToken);
        response.setStatus(HttpServletResponse.SC_OK);
        return null;
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw Throwables.propagate(e);
    }
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) UserProfile(org.pac4j.core.profile.UserProfile) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) J2EContext(org.pac4j.core.context.J2EContext) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) OAuthToken(org.apereo.cas.ticket.OAuthToken) RefreshToken(org.apereo.cas.ticket.refreshtoken.RefreshToken) Authentication(org.apereo.cas.authentication.Authentication) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 4 with UserProfile

use of org.pac4j.core.profile.UserProfile in project cas by apereo.

the class OidcIdTokenGeneratorService method produceIdTokenClaims.

/**
     * Produce id token claims jwt claims.
     *
     * @param request       the request
     * @param accessTokenId the access token id
     * @param timeout       the timeout
     * @param service       the service
     * @param profile       the user profile
     * @param context       the context
     * @param responseType  the response type
     * @return the jwt claims
     */
protected JwtClaims produceIdTokenClaims(final HttpServletRequest request, final AccessToken accessTokenId, final long timeout, final OidcRegisteredService service, final UserProfile profile, final J2EContext context, final OAuth20ResponseTypes responseType) {
    final Authentication authentication = accessTokenId.getAuthentication();
    final Principal principal = authentication.getPrincipal();
    final JwtClaims claims = new JwtClaims();
    claims.setJwtId(UUID.randomUUID().toString());
    claims.setIssuer(this.issuer);
    claims.setAudience(service.getClientId());
    final NumericDate expirationDate = NumericDate.now();
    expirationDate.addSeconds(timeout);
    claims.setExpirationTime(expirationDate);
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(this.skew);
    claims.setSubject(principal.getId());
    if (authentication.getAttributes().containsKey(casProperties.getAuthn().getMfa().getAuthenticationContextAttribute())) {
        final Collection<Object> val = CollectionUtils.toCollection(authentication.getAttributes().get(casProperties.getAuthn().getMfa().getAuthenticationContextAttribute()));
        claims.setStringClaim(OidcConstants.ACR, val.iterator().next().toString());
    }
    if (authentication.getAttributes().containsKey(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS)) {
        final Collection<Object> val = CollectionUtils.toCollection(authentication.getAttributes().get(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS));
        claims.setStringListClaim(OidcConstants.AMR, val.toArray(new String[] {}));
    }
    claims.setClaim(OAuthConstants.STATE, authentication.getAttributes().get(OAuthConstants.STATE));
    claims.setClaim(OAuthConstants.NONCE, authentication.getAttributes().get(OAuthConstants.NONCE));
    claims.setClaim(OidcConstants.CLAIM_AT_HASH, generateAccessTokenHash(accessTokenId, service));
    principal.getAttributes().entrySet().stream().filter(entry -> casProperties.getAuthn().getOidc().getClaims().contains(entry.getKey())).forEach(entry -> claims.setClaim(entry.getKey(), entry.getValue()));
    if (!claims.hasClaim(OidcConstants.CLAIM_PREFERRED_USERNAME)) {
        claims.setClaim(OidcConstants.CLAIM_PREFERRED_USERNAME, profile.getId());
    }
    return claims;
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) Arrays(java.util.Arrays) AlgorithmIdentifiers(org.jose4j.jws.AlgorithmIdentifiers) LoggerFactory(org.slf4j.LoggerFactory) DigestUtils(org.apereo.cas.util.DigestUtils) Autowired(org.springframework.beans.factory.annotation.Autowired) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) Authentication(org.apereo.cas.authentication.Authentication) CollectionUtils(org.apereo.cas.util.CollectionUtils) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) Logger(org.slf4j.Logger) OidcConstants(org.apereo.cas.oidc.OidcConstants) Collection(java.util.Collection) OAuthConstants(org.apereo.cas.support.oauth.OAuthConstants) HttpServletResponse(javax.servlet.http.HttpServletResponse) UUID(java.util.UUID) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ProfileManager(org.pac4j.core.profile.ProfileManager) MessageDigestAlgorithms(org.apache.commons.codec.digest.MessageDigestAlgorithms) NumericDate(org.jose4j.jwt.NumericDate) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) JwtClaims(org.jose4j.jwt.JwtClaims) J2EContext(org.pac4j.core.context.J2EContext) Optional(java.util.Optional) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) UserProfile(org.pac4j.core.profile.UserProfile) WebUtils(org.apereo.cas.web.support.WebUtils) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) Authentication(org.apereo.cas.authentication.Authentication) Principal(org.apereo.cas.authentication.principal.Principal)

Example 5 with UserProfile

use of org.pac4j.core.profile.UserProfile in project cas by apereo.

the class OAuth20AuthorizeEndpointController method redirectToCallbackRedirectUrl.

/**
     * Redirect to callback redirect url model and view.
     *
     * @param manager           the manager
     * @param registeredService the registered service
     * @param context           the context
     * @param clientId          the client id
     * @return the model and view
     * @throws Exception the exception
     */
protected ModelAndView redirectToCallbackRedirectUrl(final ProfileManager manager, final OAuthRegisteredService registeredService, final J2EContext context, final String clientId) throws Exception {
    final Optional<UserProfile> profile = manager.get(true);
    if (profile == null || !profile.isPresent()) {
        LOGGER.error("Unexpected null profile from profile manager. Request is not fully authenticated.");
        return OAuthUtils.produceUnauthorizedErrorView();
    }
    final Service service = createService(registeredService, context);
    LOGGER.debug("Created service [{}] based on registered service [{}]", service, registeredService);
    final Authentication authentication = createAuthentication(profile.get(), registeredService, context, service);
    LOGGER.debug("Created OAuth authentication [{}] for service [{}]", service, authentication);
    try {
        RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication);
    } catch (final UnauthorizedServiceException | PrincipalException e) {
        LOGGER.error(e.getMessage(), e);
        return OAuthUtils.produceUnauthorizedErrorView();
    }
    final String redirectUri = context.getRequestParameter(OAuthConstants.REDIRECT_URI);
    LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri);
    final String responseType = context.getRequestParameter(OAuthConstants.RESPONSE_TYPE);
    final String callbackUrl;
    if (isResponseType(responseType, OAuth20ResponseTypes.CODE)) {
        callbackUrl = buildCallbackUrlForAuthorizationCodeResponseType(authentication, service, redirectUri);
    } else if (isResponseType(responseType, OAuth20ResponseTypes.TOKEN)) {
        callbackUrl = buildCallbackUrlForImplicitTokenResponseType(context, authentication, service, redirectUri);
    } else {
        callbackUrl = buildCallbackUrlForTokenResponseType(context, authentication, service, redirectUri, responseType, clientId);
    }
    LOGGER.debug("callbackUrl: [{}]", callbackUrl);
    if (StringUtils.isBlank(callbackUrl)) {
        return OAuthUtils.produceUnauthorizedErrorView();
    }
    return OAuthUtils.redirectTo(callbackUrl);
}
Also used : UserProfile(org.pac4j.core.profile.UserProfile) Authentication(org.apereo.cas.authentication.Authentication) PrincipalException(org.apereo.cas.authentication.PrincipalException) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Aggregations

UserProfile (org.pac4j.core.profile.UserProfile)10 ProfileManager (org.pac4j.core.profile.ProfileManager)6 J2EContext (org.pac4j.core.context.J2EContext)5 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 Authentication (org.apereo.cas.authentication.Authentication)3 Optional (java.util.Optional)2 PreventedException (org.apereo.cas.authentication.PreventedException)2 ClientCredential (org.apereo.cas.authentication.principal.ClientCredential)2 Service (org.apereo.cas.authentication.principal.Service)2 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)2 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)2 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)2 OAuth20ResponseTypes (org.apereo.cas.support.oauth.OAuth20ResponseTypes)2 OAuthUserProfile (org.apereo.cas.support.oauth.profile.OAuthUserProfile)2 AccessToken (org.apereo.cas.ticket.accesstoken.AccessToken)2 JwtClaims (org.jose4j.jwt.JwtClaims)2 Client (org.pac4j.core.client.Client)2 WebContext (org.pac4j.core.context.WebContext)2