Search in sources :

Example 6 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException in project cas by apereo.

the class OAuth20Validator method checkServiceValid.

/**
     * Check if the service is valid.
     *
     * @param registeredService the registered service
     * @return whether the service is valid
     */
public boolean checkServiceValid(final RegisteredService registeredService) {
    if (registeredService == null) {
        return false;
    }
    final WebApplicationService service = webApplicationServiceServiceFactory.createService(registeredService.getServiceId());
    LOGGER.debug("Check registered service: [{}]", registeredService);
    try {
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(service, registeredService);
        return true;
    } catch (final UnauthorizedServiceException e) {
        return false;
    }
}
Also used : WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 7 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException 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 8 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException in project cas by apereo.

the class AbstractServiceValidateController method handleRequestInternal.

@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final WebApplicationService service = this.argumentExtractor.extractService(request);
    final String serviceTicketId = service != null ? service.getArtifactId() : null;
    if (service == null || serviceTicketId == null) {
        LOGGER.debug("Could not identify service and/or service ticket for service: [{}]", service);
        return generateErrorView(CasProtocolConstants.ERROR_CODE_INVALID_REQUEST, null, request, service);
    }
    try {
        return handleTicketValidation(request, service, serviceTicketId);
    } catch (final AbstractTicketValidationException e) {
        final String code = e.getCode();
        return generateErrorView(code, new Object[] { serviceTicketId, e.getOriginalService().getId(), service.getId() }, request, service);
    } catch (final AbstractTicketException e) {
        return generateErrorView(e.getCode(), new Object[] { serviceTicketId }, request, service);
    } catch (final UnauthorizedProxyingException e) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_UNAUTHORIZED_SERVICE_PROXY, new Object[] { service.getId() }, request, service);
    } catch (final UnauthorizedServiceException e) {
        return generateErrorView(CasProtocolConstants.ERROR_CODE_UNAUTHORIZED_SERVICE, null, request, service);
    }
}
Also used : WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) AbstractTicketValidationException(org.apereo.cas.ticket.AbstractTicketValidationException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) AbstractTicketException(org.apereo.cas.ticket.AbstractTicketException) UnauthorizedProxyingException(org.apereo.cas.services.UnauthorizedProxyingException)

Example 9 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException 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)

Example 10 with UnauthorizedServiceException

use of org.apereo.cas.services.UnauthorizedServiceException in project cas by apereo.

the class DisplayUserGraphicsBeforeAuthenticationAction method doExecute.

@Override
protected Event doExecute(final RequestContext requestContext) throws Exception {
    final String username = requestContext.getRequestParameters().get("username");
    if (StringUtils.isBlank(username)) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY);
    }
    final ByteSource graphics = repository.getGraphics(username);
    if (graphics == null || graphics.isEmpty()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY);
    }
    final byte[] image = EncodingUtils.encodeBase64ToByteArray(graphics.read());
    requestContext.getFlowScope().put("guaUsername", username);
    requestContext.getFlowScope().put("guaUserImage", new String(image, StandardCharsets.UTF_8));
    return success();
}
Also used : UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) ByteSource(com.google.common.io.ByteSource)

Aggregations

UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)19 Service (org.apereo.cas.authentication.principal.Service)8 WebApplicationService (org.apereo.cas.authentication.principal.WebApplicationService)7 RegisteredService (org.apereo.cas.services.RegisteredService)7 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)5 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)4 Authentication (org.apereo.cas.authentication.Authentication)2 RegexRegisteredService (org.apereo.cas.services.RegexRegisteredService)2 OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)2 SamlMetadataUIInfo (org.apereo.cas.support.saml.mdui.SamlMetadataUIInfo)2 AbstractTicketException (org.apereo.cas.ticket.AbstractTicketException)2 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)2 UserProfile (org.pac4j.core.profile.UserProfile)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 ByteSource (com.google.common.io.ByteSource)1 StringWriter (java.io.StringWriter)1 SecureRandom (java.security.SecureRandom)1 ZonedDateTime (java.time.ZonedDateTime)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 CentralAuthenticationService (org.apereo.cas.CentralAuthenticationService)1