Search in sources :

Example 6 with Authentication

use of org.apereo.cas.authentication.Authentication in project cas by apereo.

the class RequestParameterMultifactorAuthenticationPolicyEventResolver method resolveInternal.

@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
    final Authentication authentication = WebUtils.getAuthentication(context);
    if (service == null || authentication == null) {
        LOGGER.debug("No service or authentication is available to determine event for principal");
        return null;
    }
    if (StringUtils.isBlank(mfaRequestParameter)) {
        LOGGER.debug("No request parameter is defined to trigger multifactor authentication.");
        return null;
    }
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final String[] values = request.getParameterValues(mfaRequestParameter);
    if (values != null && values.length > 0) {
        LOGGER.debug("Received request parameter [{}] as [{}]", mfaRequestParameter, values);
        final Map<String, MultifactorAuthenticationProvider> providerMap = WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
        if (providerMap == null || providerMap.isEmpty()) {
            LOGGER.error("No multifactor authentication providers are available in the application context to satisfy [{}]", (Object[]) values);
            throw new AuthenticationException();
        }
        final Optional<MultifactorAuthenticationProvider> providerFound = resolveProvider(providerMap, values[0]);
        if (providerFound.isPresent()) {
            final MultifactorAuthenticationProvider provider = providerFound.get();
            if (provider.isAvailable(service)) {
                LOGGER.debug("Attempting to build an event based on the authentication provider [{}] and service [{}]", provider, service.getName());
                final Event event = validateEventIdForMatchingTransitionInContext(provider.getId(), context, buildEventAttributeMap(authentication.getPrincipal(), service, provider));
                return Collections.singleton(event);
            }
            LOGGER.warn("Located multifactor provider [{}], yet the provider cannot be reached or verified", providerFound.get());
            return null;
        } else {
            LOGGER.warn("No multifactor provider could be found for request parameter [{}]", (Object[]) values);
            throw new AuthenticationException();
        }
    }
    LOGGER.debug("No value could be found for request parameter [{}]", mfaRequestParameter);
    return null;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RegisteredService(org.apereo.cas.services.RegisteredService) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) Event(org.springframework.webflow.execution.Event) MultifactorAuthenticationProvider(org.apereo.cas.services.MultifactorAuthenticationProvider)

Example 7 with Authentication

use of org.apereo.cas.authentication.Authentication in project cas by apereo.

the class ServiceWarningAction method doExecute.

@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final Service service = WebUtils.getService(context);
    final String ticketGrantingTicket = WebUtils.getTicketGrantingTicketId(context);
    final Authentication authentication = this.ticketRegistrySupport.getAuthenticationFrom(ticketGrantingTicket);
    if (authentication == null) {
        throw new InvalidTicketException(new AuthenticationException("No authentication found for ticket " + ticketGrantingTicket), ticketGrantingTicket);
    }
    final Credential credential = WebUtils.getCredential(context);
    final AuthenticationResultBuilder authenticationResultBuilder = authenticationSystemSupport.establishAuthenticationContextFromInitial(authentication, credential);
    final AuthenticationResult authenticationResult = authenticationResultBuilder.build(service);
    final ServiceTicket serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicket, service, authenticationResult);
    WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
    if (request.getParameterMap().containsKey("ignorewarn")) {
        if (Boolean.valueOf(request.getParameter("ignorewarn").toString())) {
            this.warnCookieGenerator.removeCookie(response);
        }
    }
    return new Event(this, CasWebflowConstants.STATE_ID_REDIRECT);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Credential(org.apereo.cas.authentication.Credential) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) Authentication(org.apereo.cas.authentication.Authentication) InvalidTicketException(org.apereo.cas.ticket.InvalidTicketException) HttpServletResponse(javax.servlet.http.HttpServletResponse) CentralAuthenticationService(org.apereo.cas.CentralAuthenticationService) Service(org.apereo.cas.authentication.principal.Service) Event(org.springframework.webflow.execution.Event) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) AuthenticationResultBuilder(org.apereo.cas.authentication.AuthenticationResultBuilder) AuthenticationResult(org.apereo.cas.authentication.AuthenticationResult)

Example 8 with Authentication

use of org.apereo.cas.authentication.Authentication in project cas by apereo.

the class HazelcastTicketRegistryReplicationTests method verifyDeleteTicketWithPGT.

@Test
public void verifyDeleteTicketWithPGT() {
    final Authentication a = CoreAuthenticationTestUtils.getAuthentication();
    this.hzTicketRegistry1.addTicket(new TicketGrantingTicketImpl(TGT_ID, a, new NeverExpiresExpirationPolicy()));
    final TicketGrantingTicket tgt = this.hzTicketRegistry1.getTicket(TGT_ID, TicketGrantingTicket.class);
    final Service service = RegisteredServiceTestUtils.getService("TGT_DELETE_TEST");
    final ServiceTicket st1 = tgt.grantServiceTicket(ST_ID_1, service, new NeverExpiresExpirationPolicy(), false, true);
    this.hzTicketRegistry1.addTicket(st1);
    assertNotNull(this.hzTicketRegistry1.getTicket(TGT_ID, TicketGrantingTicket.class));
    assertNotNull(this.hzTicketRegistry1.getTicket(ST_ID_1, ServiceTicket.class));
    final ProxyGrantingTicket pgt = st1.grantProxyGrantingTicket(PGT_ID_1, a, new NeverExpiresExpirationPolicy());
    assertEquals(a, pgt.getAuthentication());
    this.hzTicketRegistry1.addTicket(pgt);
    this.hzTicketRegistry1.updateTicket(tgt);
    assertSame(3, this.hzTicketRegistry1.deleteTicket(tgt.getId()));
    assertNull(this.hzTicketRegistry1.getTicket(TGT_ID, TicketGrantingTicket.class));
    assertNull(this.hzTicketRegistry1.getTicket(ST_ID_1, ServiceTicket.class));
    assertNull(this.hzTicketRegistry1.getTicket(PGT_ID_1, ProxyGrantingTicket.class));
}
Also used : NeverExpiresExpirationPolicy(org.apereo.cas.ticket.support.NeverExpiresExpirationPolicy) Authentication(org.apereo.cas.authentication.Authentication) TicketGrantingTicket(org.apereo.cas.ticket.TicketGrantingTicket) MockTicketGrantingTicket(org.apereo.cas.mock.MockTicketGrantingTicket) Service(org.apereo.cas.authentication.principal.Service) TicketGrantingTicketImpl(org.apereo.cas.ticket.TicketGrantingTicketImpl) MockServiceTicket(org.apereo.cas.mock.MockServiceTicket) ServiceTicket(org.apereo.cas.ticket.ServiceTicket) ProxyGrantingTicket(org.apereo.cas.ticket.proxy.ProxyGrantingTicket) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 9 with Authentication

use of org.apereo.cas.authentication.Authentication in project cas by apereo.

the class ECPProfileHandlerController method handleEcpRequest.

/**
     * Handle ecp request.
     *
     * @param response    the response
     * @param request     the request
     * @param soapContext the soap context
     * @param credential  the credential
     */
protected void handleEcpRequest(final HttpServletResponse response, final HttpServletRequest request, final MessageContext soapContext, final Credential credential) {
    final Envelope envelope = soapContext.getSubcontext(SOAP11Context.class).getEnvelope();
    SamlUtils.logSamlObject(configBean, envelope);
    final AuthnRequest authnRequest = (AuthnRequest) soapContext.getMessage();
    final Pair<AuthnRequest, MessageContext> authenticationContext = Pair.of(authnRequest, soapContext);
    try {
        final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> serviceRequest = verifySamlAuthenticationRequest(authenticationContext, request);
        final Authentication authentication = authenticateEcpRequest(credential, authenticationContext);
        buildSamlResponse(response, request, authenticationContext, buildEcpCasAssertion(authentication, serviceRequest.getKey()));
    } catch (final AuthenticationException e) {
        LOGGER.error(e.getMessage(), e);
        final String error = e.getHandlerErrors().values().stream().map(Class::getSimpleName).collect(Collectors.joining(","));
        buildEcpFaultResponse(response, request, Pair.of(authnRequest, error));
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        buildEcpFaultResponse(response, request, Pair.of(authnRequest, e.getMessage()));
    }
}
Also used : AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Envelope(org.opensaml.soap.soap11.Envelope) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SOAP11Context(org.opensaml.soap.messaging.context.SOAP11Context) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Authentication(org.apereo.cas.authentication.Authentication) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) MessageContext(org.opensaml.messaging.context.MessageContext)

Example 10 with Authentication

use of org.apereo.cas.authentication.Authentication 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)

Aggregations

Authentication (org.apereo.cas.authentication.Authentication)125 RegisteredService (org.apereo.cas.services.RegisteredService)58 Service (org.apereo.cas.authentication.principal.Service)44 lombok.val (lombok.val)38 HttpServletRequest (javax.servlet.http.HttpServletRequest)32 Slf4j (lombok.extern.slf4j.Slf4j)32 Principal (org.apereo.cas.authentication.principal.Principal)26 Event (org.springframework.webflow.execution.Event)25 Optional (java.util.Optional)23 TicketGrantingTicket (org.apereo.cas.ticket.TicketGrantingTicket)22 Test (org.junit.Test)21 MultifactorAuthenticationProvider (org.apereo.cas.services.MultifactorAuthenticationProvider)20 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)19 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)17 Collection (java.util.Collection)16 StringUtils (org.apache.commons.lang3.StringUtils)16 AuthenticationResult (org.apereo.cas.authentication.AuthenticationResult)15 ServiceTicket (org.apereo.cas.ticket.ServiceTicket)15 WebUtils (org.apereo.cas.web.support.WebUtils)14 RequestContext (org.springframework.webflow.execution.RequestContext)14