Search in sources :

Example 1 with J2EContext

use of org.pac4j.core.context.J2EContext 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 2 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class OAuth20AuthorizeEndpointController 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
     */
@GetMapping(path = OAuthConstants.BASE_OAUTH20_URL + '/' + OAuthConstants.AUTHORIZE_URL)
public ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
    if (!verifyAuthorizeRequest(request) || !isRequestAuthenticated(manager, context)) {
        LOGGER.error("Authorize request verification failed");
        return OAuthUtils.produceUnauthorizedErrorView();
    }
    final String clientId = context.getRequestParameter(OAuthConstants.CLIENT_ID);
    final OAuthRegisteredService registeredService = getRegisteredServiceByClientId(clientId);
    try {
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(clientId, registeredService);
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        return OAuthUtils.produceUnauthorizedErrorView();
    }
    final ModelAndView mv = this.consentApprovalViewResolver.resolve(context, registeredService);
    if (!mv.isEmpty() && mv.hasView()) {
        return mv;
    }
    return redirectToCallbackRedirectUrl(manager, registeredService, context, clientId);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ModelAndView(org.springframework.web.servlet.ModelAndView) J2EContext(org.pac4j.core.context.J2EContext) PrincipalException(org.apereo.cas.authentication.PrincipalException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 3 with J2EContext

use of org.pac4j.core.context.J2EContext in project cas by apereo.

the class AccessTokenPasswordGrantRequestExtractor method extract.

@Override
public AccessTokenRequestDataHolder extract(final HttpServletRequest request, final HttpServletResponse response) {
    final String clientId = request.getParameter(OAuth20Constants.CLIENT_ID);
    final Set<String> scopes = OAuth20Utils.parseRequestScopes(request);
    LOGGER.debug("Locating OAuth registered service by client id [{}]", clientId);
    final OAuthRegisteredService registeredService = OAuth20Utils.getRegisteredOAuthServiceByClientId(this.servicesManager, clientId);
    LOGGER.debug("Located OAuth registered service [{}]", registeredService);
    final J2EContext context = Pac4jUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = Pac4jUtils.getPac4jProfileManager(request, response);
    final Optional<UserProfile> profile = manager.get(true);
    if (!profile.isPresent()) {
        throw new UnauthorizedServiceException("OAuth user profile cannot be determined");
    }
    final UserProfile uProfile = profile.get();
    LOGGER.debug("Creating matching service request based on [{}]", registeredService);
    final boolean requireServiceHeader = oAuthProperties.getGrants().getResourceOwner().isRequireServiceHeader();
    if (requireServiceHeader) {
        LOGGER.debug("Using request headers to identify and build the target service url");
    }
    final Service service = this.authenticationBuilder.buildService(registeredService, context, requireServiceHeader);
    LOGGER.debug("Authenticating the OAuth request indicated by [{}]", service);
    final Authentication authentication = this.authenticationBuilder.build(uProfile, registeredService, context, service);
    final AuditableContext audit = AuditableContext.builder().service(service).authentication(authentication).registeredService(registeredService).retrievePrincipalAttributesFromReleasePolicy(Boolean.TRUE).build();
    final AuditableExecutionResult accessResult = this.registeredServiceAccessStrategyEnforcer.execute(audit);
    accessResult.throwExceptionIfNeeded();
    final AuthenticationResult result = new DefaultAuthenticationResult(authentication, requireServiceHeader ? service : null);
    final TicketGrantingTicket ticketGrantingTicket = this.centralAuthenticationService.createTicketGrantingTicket(result);
    return new AccessTokenRequestDataHolder(service, authentication, registeredService, ticketGrantingTicket, getGrantType(), scopes);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) AuditableContext(org.apereo.cas.audit.AuditableContext) UserProfile(org.pac4j.core.profile.UserProfile) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) Service(org.apereo.cas.authentication.principal.Service) J2EContext(org.pac4j.core.context.J2EContext) DefaultAuthenticationResult(org.apereo.cas.authentication.DefaultAuthenticationResult) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult) DefaultAuthenticationResult(org.apereo.cas.authentication.DefaultAuthenticationResult) Authentication(org.apereo.cas.authentication.Authentication) AuditableExecutionResult(org.apereo.cas.audit.AuditableExecutionResult)

Example 4 with J2EContext

use of org.pac4j.core.context.J2EContext 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 OidcProperties oidc = casProperties.getAuthn().getOidc();
    final JwtClaims claims = new JwtClaims();
    claims.setJwtId(getOAuthServiceTicket(accessTokenId.getTicketGrantingTicket()).getKey());
    claims.setIssuer(oidc.getIssuer());
    claims.setAudience(service.getClientId());
    final NumericDate expirationDate = NumericDate.now();
    expirationDate.addSeconds(timeout);
    claims.setExpirationTime(expirationDate);
    claims.setIssuedAtToNow();
    claims.setNotBeforeMinutesInThePast(oidc.getSkew());
    claims.setSubject(principal.getId());
    final MultifactorAuthenticationProperties mfa = casProperties.getAuthn().getMfa();
    final Map<String, Object> attributes = authentication.getAttributes();
    if (attributes.containsKey(mfa.getAuthenticationContextAttribute())) {
        final Collection<Object> val = CollectionUtils.toCollection(attributes.get(mfa.getAuthenticationContextAttribute()));
        claims.setStringClaim(OidcConstants.ACR, val.iterator().next().toString());
    }
    if (attributes.containsKey(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS)) {
        final Collection<Object> val = CollectionUtils.toCollection(attributes.get(AuthenticationHandler.SUCCESSFUL_AUTHENTICATION_HANDLERS));
        claims.setStringListClaim(OidcConstants.AMR, val.toArray(new String[] {}));
    }
    claims.setClaim(OAuth20Constants.STATE, attributes.get(OAuth20Constants.STATE));
    claims.setClaim(OAuth20Constants.NONCE, attributes.get(OAuth20Constants.NONCE));
    claims.setClaim(OidcConstants.CLAIM_AT_HASH, generateAccessTokenHash(accessTokenId, service));
    principal.getAttributes().entrySet().stream().filter(entry -> oidc.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) DigestUtils(org.apereo.cas.util.DigestUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationHandler(org.apereo.cas.authentication.AuthenticationHandler) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) Authentication(org.apereo.cas.authentication.Authentication) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) AccessToken(org.apereo.cas.ticket.accesstoken.AccessToken) ServicesManager(org.apereo.cas.services.ServicesManager) OAuth20Constants(org.apereo.cas.support.oauth.OAuth20Constants) OAuth20ResponseTypes(org.apereo.cas.support.oauth.OAuth20ResponseTypes) OidcConstants(org.apereo.cas.oidc.OidcConstants) Collection(java.util.Collection) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) ProfileManager(org.pac4j.core.profile.ProfileManager) StandardCharsets(java.nio.charset.StandardCharsets) Pac4jUtils(org.apereo.cas.util.Pac4jUtils) Slf4j(lombok.extern.slf4j.Slf4j) MessageDigestAlgorithms(org.apache.commons.codec.digest.MessageDigestAlgorithms) NumericDate(org.jose4j.jwt.NumericDate) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) Stream(java.util.stream.Stream) JwtClaims(org.jose4j.jwt.JwtClaims) Service(org.apereo.cas.authentication.principal.Service) Entry(java.util.Map.Entry) J2EContext(org.pac4j.core.context.J2EContext) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Principal(org.apereo.cas.authentication.principal.Principal) EncodingUtils(org.apereo.cas.util.EncodingUtils) UserProfile(org.pac4j.core.profile.UserProfile) NumericDate(org.jose4j.jwt.NumericDate) JwtClaims(org.jose4j.jwt.JwtClaims) Authentication(org.apereo.cas.authentication.Authentication) OidcProperties(org.apereo.cas.configuration.model.support.oidc.OidcProperties) MultifactorAuthenticationProperties(org.apereo.cas.configuration.model.support.mfa.MultifactorAuthenticationProperties) Principal(org.apereo.cas.authentication.principal.Principal)

Example 5 with J2EContext

use of org.pac4j.core.context.J2EContext in project knox by apache.

the class Pac4jIdentityAdapter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    final J2EContext context = new J2EContext(request, response, ((Config) request.getAttribute(PAC4J_CONFIG)).getSessionStore());
    final ProfileManager<CommonProfile> manager = new ProfileManager<CommonProfile>(context);
    final Optional<CommonProfile> optional = manager.get(true);
    if (optional.isPresent()) {
        CommonProfile profile = optional.get();
        logger.debug("User authenticated as: {}", profile);
        manager.remove(true);
        String id = null;
        if (idAttribute != null) {
            Object attribute = profile.getAttribute(idAttribute);
            if (attribute != null) {
                id = attribute.toString();
            }
            if (id == null) {
                logger.error("Invalid attribute_id: {} configured to be used as principal" + " falling back to default id", idAttribute);
            }
        }
        if (id == null) {
            id = profile.getId();
        }
        testIdentifier = id;
        PrimaryPrincipal pp = new PrimaryPrincipal(id);
        Subject subject = new Subject();
        subject.getPrincipals().add(pp);
        auditService.getContext().setUsername(id);
        String sourceUri = (String) request.getAttribute(AbstractGatewayFilter.SOURCE_REQUEST_CONTEXT_URL_ATTRIBUTE_NAME);
        auditor.audit(Action.AUTHENTICATION, sourceUri, ResourceType.URI, ActionOutcome.SUCCESS);
        doAs(request, response, chain, subject);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ProfileManager(org.pac4j.core.profile.ProfileManager) CommonProfile(org.pac4j.core.profile.CommonProfile) PrimaryPrincipal(org.apache.knox.gateway.security.PrimaryPrincipal) HttpServletResponse(javax.servlet.http.HttpServletResponse) J2EContext(org.pac4j.core.context.J2EContext) Subject(javax.security.auth.Subject)

Aggregations

J2EContext (org.pac4j.core.context.J2EContext)32 RedirectAction (org.pac4j.core.redirect.RedirectAction)13 Test (org.junit.Test)11 WebContext (org.pac4j.core.context.WebContext)11 ProfileManager (org.pac4j.core.profile.ProfileManager)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)11 HttpServletRequest (javax.servlet.http.HttpServletRequest)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)6 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)6 UserProfile (org.pac4j.core.profile.UserProfile)6 GetMapping (org.springframework.web.bind.annotation.GetMapping)6 Service (org.apereo.cas.authentication.principal.Service)5 Authentication (org.apereo.cas.authentication.Authentication)4 AccessToken (org.apereo.cas.ticket.accesstoken.AccessToken)4 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)3 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)2 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)2 PrincipalException (org.apereo.cas.authentication.PrincipalException)2