Search in sources :

Example 6 with UserProfile

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

the class OidcSecurityInterceptor method preHandle.

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
    final J2EContext ctx = WebUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
    boolean clearCreds = false;
    final Optional<UserProfile> auth = authorizationRequestSupport.isAuthenticationProfileAvailable(ctx);
    if (auth.isPresent()) {
        final Optional<Long> maxAge = authorizationRequestSupport.getOidcMaxAgeFromAuthorizationRequest(ctx);
        if (maxAge.isPresent()) {
            clearCreds = authorizationRequestSupport.isCasAuthenticationOldForMaxAgeAuthorizationRequest(ctx, auth.get());
        }
    }
    final Set<String> prompts = authorizationRequestSupport.getOidcPromptFromAuthorizationRequest(ctx);
    if (!clearCreds) {
        clearCreds = prompts.contains(OidcConstants.PROMPT_LOGIN);
    }
    if (clearCreds) {
        clearCreds = !prompts.contains(OidcConstants.PROMPT_NONE);
    }
    if (clearCreds) {
        manager.remove(true);
    }
    return super.preHandle(request, response, handler);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) J2EContext(org.pac4j.core.context.J2EContext)

Example 7 with UserProfile

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

the class OidcIdTokenGeneratorService method generate.

/**
     * Generate string.
     *
     * @param request           the request
     * @param response          the response
     * @param accessTokenId     the access token id
     * @param timeout           the timeout
     * @param responseType      the response type
     * @param registeredService the registered service
     * @return the string
     * @throws Exception the exception
     */
public String generate(final HttpServletRequest request, final HttpServletResponse response, final AccessToken accessTokenId, final long timeout, final OAuth20ResponseTypes responseType, final OAuthRegisteredService registeredService) throws Exception {
    final OidcRegisteredService oidcRegisteredService = (OidcRegisteredService) registeredService;
    final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
    final Optional<UserProfile> profile = manager.get(true);
    LOGGER.debug("Attempting to produce claims for the id token [{}]", accessTokenId);
    final JwtClaims claims = produceIdTokenClaims(request, accessTokenId, timeout, oidcRegisteredService, profile.get(), context, responseType);
    LOGGER.debug("Produce claims for the id token [{}] as [{}]", accessTokenId, claims);
    return this.signingService.encode(oidcRegisteredService, claims);
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) JwtClaims(org.jose4j.jwt.JwtClaims) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) J2EContext(org.pac4j.core.context.J2EContext)

Example 8 with UserProfile

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

the class WebUtils method getAuthenticatedUsername.

/**
     * Return the username of the authenticated user (based on pac4j security).
     *
     * @return the authenticated username.
     */
public static String getAuthenticatedUsername() {
    final HttpServletRequest request = getHttpServletRequestFromRequestAttributes();
    final HttpServletResponse response = getHttpServletResponseFromRequestAttributes();
    if (request != null && response != null) {
        final ProfileManager manager = getPac4jProfileManager(request, response);
        final Optional<UserProfile> profile = manager.get(true);
        if (profile != null && profile.isPresent()) {
            final String id = profile.get().getId();
            if (id != null) {
                return id;
            }
        }
    }
    return PrincipalResolver.UNKNOWN_USER;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ProfileManager(org.pac4j.core.profile.ProfileManager) UserProfile(org.pac4j.core.profile.UserProfile) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 9 with UserProfile

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

the class OAuth20AccessTokenEndpointController method verifyAccessTokenRequest.

/**
     * Verify the access token request.
     *
     * @param request  the HTTP request
     * @param response the HTTP response
     * @return true, if successful
     */
private boolean verifyAccessTokenRequest(final HttpServletRequest request, final HttpServletResponse response) {
    // must have the right grant type
    final String grantType = request.getParameter(OAuthConstants.GRANT_TYPE);
    if (!checkGrantTypes(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE, OAuth20GrantTypes.PASSWORD, OAuth20GrantTypes.REFRESH_TOKEN)) {
        return false;
    }
    // must be authenticated (client or user)
    final J2EContext context = WebUtils.getPac4jJ2EContext(request, response);
    final ProfileManager manager = WebUtils.getPac4jProfileManager(request, response);
    final Optional<UserProfile> profile = manager.get(true);
    if (profile == null || !profile.isPresent()) {
        return false;
    }
    final UserProfile uProfile = profile.get();
    // authorization code grant type
    if (isGrantType(grantType, OAuth20GrantTypes.AUTHORIZATION_CODE)) {
        final String clientId = uProfile.getId();
        final String redirectUri = request.getParameter(OAuthConstants.REDIRECT_URI);
        final OAuthRegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
        return uProfile instanceof OAuthClientProfile && getValidator().checkParameterExist(request, OAuthConstants.REDIRECT_URI) && getValidator().checkParameterExist(request, OAuthConstants.CODE) && getValidator().checkCallbackValid(registeredService, redirectUri);
    } else if (isGrantType(grantType, OAuth20GrantTypes.REFRESH_TOKEN)) {
        // refresh token grant type
        return uProfile instanceof OAuthClientProfile && getValidator().checkParameterExist(request, OAuthConstants.REFRESH_TOKEN);
    } else {
        final String clientId = request.getParameter(OAuthConstants.CLIENT_ID);
        final OAuthRegisteredService registeredService = OAuthUtils.getRegisteredOAuthService(getServicesManager(), clientId);
        // resource owner password grant type
        return uProfile instanceof OAuthUserProfile && getValidator().checkParameterExist(request, OAuthConstants.CLIENT_ID) && getValidator().checkServiceValid(registeredService);
    }
}
Also used : ProfileManager(org.pac4j.core.profile.ProfileManager) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile) UserProfile(org.pac4j.core.profile.UserProfile) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) OAuthClientProfile(org.apereo.cas.support.oauth.profile.OAuthClientProfile) J2EContext(org.pac4j.core.context.J2EContext) OAuthUserProfile(org.apereo.cas.support.oauth.profile.OAuthUserProfile)

Example 10 with UserProfile

use of org.pac4j.core.profile.UserProfile in project ratpack by ratpack.

the class Pac4jAuthenticator method handle.

@Override
public void handle(Context ctx) throws Exception {
    PathBinding pathBinding = ctx.getPathBinding();
    String pastBinding = pathBinding.getPastBinding();
    if (pastBinding.equals(path)) {
        RatpackWebContext.from(ctx, true).flatMap(webContext -> {
            SessionData sessionData = webContext.getSession();
            return createClients(ctx, pathBinding).map(clients -> clients.findClient(webContext)).map(Types::<Client<Credentials, UserProfile>>cast).flatMap(client -> getProfile(webContext, client)).map(profile -> {
                if (profile != null) {
                    sessionData.set(Pac4jSessionKeys.USER_PROFILE, profile);
                }
                Optional<String> originalUrl = sessionData.get(Pac4jSessionKeys.REQUESTED_URL);
                sessionData.remove(Pac4jSessionKeys.REQUESTED_URL);
                return originalUrl;
            }).onError(t -> {
                if (t instanceof RequiresHttpAction) {
                    webContext.sendResponse((RequiresHttpAction) t);
                } else {
                    ctx.error(new TechnicalException("Failed to get user profile", t));
                }
            });
        }).then(originalUrlOption -> {
            ctx.redirect(originalUrlOption.orElse("/"));
        });
    } else {
        createClients(ctx, pathBinding).then(clients -> {
            Registry registry = Registry.singleLazy(Clients.class, () -> uncheck(() -> clients));
            ctx.next(registry);
        });
    }
}
Also used : Types(ratpack.util.Types) Context(ratpack.handling.Context) RatpackPac4j(ratpack.pac4j.RatpackPac4j) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) Promise(ratpack.exec.Promise) PublicAddress(ratpack.server.PublicAddress) Blocking(ratpack.exec.Blocking) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) WebContext(org.pac4j.core.context.WebContext) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) Handler(ratpack.handling.Handler) Registry(ratpack.registry.Registry) Optional(java.util.Optional) PathBinding(ratpack.path.PathBinding) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Credentials(org.pac4j.core.credentials.Credentials) Types(ratpack.util.Types) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Registry(ratpack.registry.Registry) PathBinding(ratpack.path.PathBinding) Credentials(org.pac4j.core.credentials.Credentials)

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