Search in sources :

Example 1 with ProfileManager

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

the class TerminateSessionAction method destroyApplicationSession.

/**
     * Destroy application session.
     * Also kills all delegated authn profiles via pac4j.
     *
     * @param request  the request
     * @param response the response
     */
protected void destroyApplicationSession(final HttpServletRequest request, final HttpServletResponse response) {
    LOGGER.debug("Destroying application session");
    final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
    manager.logout();
    final HttpSession session = request.getSession();
    if (session != null) {
        session.invalidate();
    }
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) HttpSession(javax.servlet.http.HttpSession)

Example 2 with ProfileManager

use of org.pac4j.core.profile.ProfileManager 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 3 with ProfileManager

use of org.pac4j.core.profile.ProfileManager 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 4 with ProfileManager

use of org.pac4j.core.profile.ProfileManager 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 5 with ProfileManager

use of org.pac4j.core.profile.ProfileManager 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

ProfileManager (org.pac4j.core.profile.ProfileManager)20 J2EContext (org.pac4j.core.context.J2EContext)10 UserProfile (org.pac4j.core.profile.UserProfile)9 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)4 GetMapping (org.springframework.web.bind.annotation.GetMapping)4 Authentication (org.apereo.cas.authentication.Authentication)3 CommonProfile (org.pac4j.core.profile.CommonProfile)3 HttpSession (javax.servlet.http.HttpSession)2 PrincipalException (org.apereo.cas.authentication.PrincipalException)2 Service (org.apereo.cas.authentication.principal.Service)2 OAuthUserProfile (org.apereo.cas.support.oauth.profile.OAuthUserProfile)2 Client (org.pac4j.core.client.Client)2 Clients (org.pac4j.core.client.Clients)2 HttpAction (org.pac4j.core.exception.HttpAction)2 Subject (javax.security.auth.Subject)1 PrimaryPrincipal (org.apache.knox.gateway.security.PrimaryPrincipal)1 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)1