Search in sources :

Example 1 with OAuthRegisteredService

use of org.apereo.cas.support.oauth.services.OAuthRegisteredService in project cas by apereo.

the class OidcAuthorizeEndpointController method getRegisteredServiceByClientId.

@Override
protected OAuthRegisteredService getRegisteredServiceByClientId(final String clientId) {
    final OAuthRegisteredService service = super.getRegisteredServiceByClientId(clientId);
    scopeToAttributesFilter.reconcile(service);
    return service;
}
Also used : OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService)

Example 2 with OAuthRegisteredService

use of org.apereo.cas.support.oauth.services.OAuthRegisteredService in project cas by apereo.

the class DefaultRegisteredServiceMapper method mapRegisteredService.

@Override
public void mapRegisteredService(final RegisteredService svc, final RegisteredServiceEditBean.ServiceData bean) {
    bean.setAssignedId(Long.toString(svc.getId()));
    bean.setServiceId(svc.getServiceId());
    bean.setName(svc.getName());
    bean.setDescription(svc.getDescription());
    if (svc.getLogo() != null) {
        bean.setLogoUrl(svc.getLogo().toExternalForm());
    }
    bean.setRequiredHandlers(svc.getRequiredHandlers());
    if (StringUtils.isNotBlank(svc.getInformationUrl())) {
        bean.setInformationUrl(svc.getInformationUrl());
    }
    if (StringUtils.isNotBlank(svc.getPrivacyUrl())) {
        bean.setPrivacyUrl(svc.getPrivacyUrl());
    }
    if (svc instanceof OAuthRegisteredService) {
        bean.setType(RegisteredServiceTypeEditBean.OAUTH.toString());
        final OAuthRegisteredService oauth = (OAuthRegisteredService) svc;
        final RegisteredServiceOAuthTypeEditBean oauthBean = bean.getOauth();
        oauthBean.setBypass(oauth.isBypassApprovalPrompt());
        oauthBean.setClientId(oauth.getClientId());
        oauthBean.setClientSecret(oauth.getClientSecret());
        oauthBean.setRefreshToken(oauth.isGenerateRefreshToken());
        oauthBean.setJsonFormat(oauth.isJsonFormat());
        if (svc instanceof OidcRegisteredService) {
            bean.setType(RegisteredServiceTypeEditBean.OIDC.toString());
            final OidcRegisteredService oidc = (OidcRegisteredService) svc;
            final RegisteredServiceOidcTypeEditBean oidcBean = bean.getOidc();
            oidcBean.setJwks(oidc.getJwks());
            oidcBean.setSignToken(oidc.isSignIdToken());
            oidcBean.setImplicit(oidc.isImplicit());
            oidcBean.setEncrypt(oidc.isEncryptIdToken());
            oidcBean.setEncryptAlg(oidc.getIdTokenEncryptionAlg());
            oidcBean.setEncryptEnc(oidc.getIdTokenEncryptionEncoding());
            oidcBean.setDynamic(oidc.isDynamicallyRegistered());
            if (oidc.isDynamicallyRegistered()) {
                oidcBean.setDynamicDate(oidc.getDynamicRegistrationDateTime().toString());
            }
            oidcBean.setScopes(oidc.getScopes().stream().collect(Collectors.joining(",")));
        }
    }
    if (svc instanceof SamlRegisteredService) {
        bean.setType(RegisteredServiceTypeEditBean.SAML.toString());
        final SamlRegisteredService saml = (SamlRegisteredService) svc;
        final RegisteredServiceSamlTypeEditBean samlbean = bean.getSaml();
        samlbean.setMdLoc(saml.getMetadataLocation());
        samlbean.setMdMaxVal(saml.getMetadataMaxValidity());
        samlbean.setMdSigLoc(saml.getMetadataSignatureLocation());
        samlbean.setAuthCtxCls(saml.getRequiredAuthenticationContextClass());
        samlbean.setEncAssert(saml.isEncryptAssertions());
        samlbean.setSignResp(saml.isSignResponses());
        samlbean.setSignAssert(saml.isSignAssertions());
        samlbean.setRemoveEmptyEntities(saml.isMetadataCriteriaRemoveEmptyEntitiesDescriptors());
        samlbean.setRemoveRoleless(saml.isMetadataCriteriaRemoveRolelessEntityDescriptors());
        if (StringUtils.isNotBlank(saml.getMetadataCriteriaDirection())) {
            samlbean.setDir(saml.getMetadataCriteriaDirection().toUpperCase());
        }
        if (StringUtils.isNotBlank(saml.getMetadataCriteriaPattern())) {
            samlbean.setMdPattern(saml.getMetadataCriteriaPattern());
        }
        if (StringUtils.isNotBlank(saml.getMetadataCriteriaRoles())) {
            samlbean.setRoles(org.springframework.util.StringUtils.commaDelimitedListToSet(saml.getMetadataCriteriaRoles()));
        }
    }
    bean.setTheme(svc.getTheme());
    bean.setEvalOrder(svc.getEvaluationOrder());
    final LogoutType logoutType = svc.getLogoutType();
    switch(logoutType) {
        case BACK_CHANNEL:
            bean.setLogoutType(RegisteredServiceLogoutTypeEditBean.BACK.toString());
            break;
        case FRONT_CHANNEL:
            bean.setLogoutType(RegisteredServiceLogoutTypeEditBean.FRONT.toString());
            break;
        default:
            bean.setLogoutType(RegisteredServiceLogoutTypeEditBean.NONE.toString());
            break;
    }
    final URL url = svc.getLogoutUrl();
    if (url != null) {
        bean.setLogoutUrl(url.toExternalForm());
    }
    final RegisteredServicePublicKey key = svc.getPublicKey();
    final RegisteredServicePublicKeyEditBean pBean = bean.getPublicKey();
    if (key != null) {
        pBean.setAlgorithm(key.getAlgorithm());
        pBean.setLocation(key.getLocation());
    }
    final Map<String, RegisteredServiceProperty> props = svc.getProperties();
    final Set<RegisteredServiceEditBean.ServiceData.PropertyBean> beanProps = bean.getProperties();
    props.entrySet().forEach(p -> {
        final String set = org.springframework.util.StringUtils.collectionToCommaDelimitedString(p.getValue().getValues());
        beanProps.add(new RegisteredServiceEditBean.ServiceData.PropertyBean(p.getKey(), set));
    });
}
Also used : RegisteredServicePublicKey(org.apereo.cas.services.RegisteredServicePublicKey) RegisteredServiceOAuthTypeEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceOAuthTypeEditBean) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) RegisteredServiceOidcTypeEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceOidcTypeEditBean) RegisteredServicePublicKeyEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServicePublicKeyEditBean) RegisteredServiceEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceEditBean) URL(java.net.URL) RegisteredServiceSamlTypeEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceSamlTypeEditBean) RegisteredServiceProperty(org.apereo.cas.services.RegisteredServiceProperty) DefaultRegisteredServiceProperty(org.apereo.cas.services.DefaultRegisteredServiceProperty) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) LogoutType(org.apereo.cas.services.LogoutType)

Example 3 with OAuthRegisteredService

use of org.apereo.cas.support.oauth.services.OAuthRegisteredService in project cas by apereo.

the class DefaultRegisteredServiceMapper method toRegisteredService.

@Override
public RegisteredService toRegisteredService(final RegisteredServiceEditBean.ServiceData data) {
    try {
        final AbstractRegisteredService regSvc;
        // create base RegisteredService object
        final String type = data.getType();
        if (StringUtils.equalsIgnoreCase(type, RegisteredServiceTypeEditBean.OAUTH.toString()) || StringUtils.equalsIgnoreCase(type, RegisteredServiceTypeEditBean.OIDC.toString())) {
            if (StringUtils.equalsIgnoreCase(type, RegisteredServiceTypeEditBean.OAUTH.toString())) {
                regSvc = new OAuthRegisteredService();
            } else {
                regSvc = new OidcRegisteredService();
            }
            final RegisteredServiceOAuthTypeEditBean oauthBean = data.getOauth();
            ((OAuthRegisteredService) regSvc).setClientId(oauthBean.getClientId());
            ((OAuthRegisteredService) regSvc).setClientSecret(oauthBean.getClientSecret());
            ((OAuthRegisteredService) regSvc).setBypassApprovalPrompt(oauthBean.isBypass());
            ((OAuthRegisteredService) regSvc).setGenerateRefreshToken(oauthBean.isRefreshToken());
            ((OAuthRegisteredService) regSvc).setJsonFormat(oauthBean.isJsonFormat());
            if (StringUtils.equalsIgnoreCase(type, RegisteredServiceTypeEditBean.OIDC.toString())) {
                ((OidcRegisteredService) regSvc).setJwks(data.getOidc().getJwks());
                ((OidcRegisteredService) regSvc).setSignIdToken(data.getOidc().isSignToken());
                ((OidcRegisteredService) regSvc).setImplicit(data.getOidc().isImplicit());
                ((OidcRegisteredService) regSvc).setEncryptIdToken(data.getOidc().isEncrypt());
                ((OidcRegisteredService) regSvc).setIdTokenEncryptionAlg(data.getOidc().getEncryptAlg());
                ((OidcRegisteredService) regSvc).setIdTokenEncryptionEncoding(data.getOidc().getEncryptEnc());
                ((OidcRegisteredService) regSvc).setScopes(org.springframework.util.StringUtils.commaDelimitedListToSet(data.getOidc().getScopes()));
            }
        } else if (StringUtils.equalsIgnoreCase(type, RegisteredServiceTypeEditBean.SAML.toString())) {
            regSvc = new SamlRegisteredService();
            final RegisteredServiceSamlTypeEditBean samlBean = data.getSaml();
            ((SamlRegisteredService) regSvc).setEncryptAssertions(samlBean.isEncAssert());
            ((SamlRegisteredService) regSvc).setSignAssertions(samlBean.isSignAssert());
            ((SamlRegisteredService) regSvc).setSignResponses(samlBean.isSignResp());
            ((SamlRegisteredService) regSvc).setMetadataLocation(samlBean.getMdLoc());
            ((SamlRegisteredService) regSvc).setMetadataSignatureLocation(samlBean.getMdSigLoc());
            ((SamlRegisteredService) regSvc).setMetadataMaxValidity(samlBean.getMdMaxVal());
            ((SamlRegisteredService) regSvc).setRequiredAuthenticationContextClass(samlBean.getAuthCtxCls());
            ((SamlRegisteredService) regSvc).setMetadataCriteriaRemoveEmptyEntitiesDescriptors(samlBean.isRemoveEmptyEntities());
            ((SamlRegisteredService) regSvc).setMetadataCriteriaRemoveRolelessEntityDescriptors(samlBean.isRemoveRoleless());
            if (StringUtils.isNotBlank(samlBean.getDir())) {
                ((SamlRegisteredService) regSvc).setMetadataCriteriaDirection(samlBean.getDir().toUpperCase());
            }
            if (StringUtils.isNotBlank(samlBean.getMdPattern()) && RegexUtils.isValidRegex(samlBean.getMdPattern())) {
                ((SamlRegisteredService) regSvc).setMetadataCriteriaPattern(samlBean.getMdPattern());
            }
            if (samlBean.getRoles() != null && !samlBean.getRoles().isEmpty()) {
                ((SamlRegisteredService) regSvc).setMetadataCriteriaRoles(org.springframework.util.StringUtils.collectionToCommaDelimitedString(samlBean.getRoles()));
            }
        } else {
            if (RegexUtils.isValidRegex(data.getServiceId())) {
                regSvc = new RegexRegisteredService();
            } else {
                throw new RuntimeException("Invalid service type.");
            }
        }
        // set the assigned Id
        final long assignedId = Long.parseLong(data.getAssignedId());
        if (assignedId <= 0) {
            regSvc.setId(RegisteredService.INITIAL_IDENTIFIER_VALUE);
        } else {
            regSvc.setId(assignedId);
        }
        // set simple RegisteredService properties
        regSvc.setServiceId(data.getServiceId());
        regSvc.setName(data.getName());
        regSvc.setDescription(data.getDescription());
        if (StringUtils.isNotBlank(data.getLogoUrl())) {
            regSvc.setLogo(new URL(data.getLogoUrl()));
        }
        regSvc.setTheme(data.getTheme());
        regSvc.setEvaluationOrder(data.getEvalOrder());
        regSvc.setRequiredHandlers(data.getRequiredHandlers());
        regSvc.setPrivacyUrl(data.getPrivacyUrl());
        regSvc.setInformationUrl(data.getInformationUrl());
        // process logout settings
        regSvc.setLogoutType(parseLogoutType(data.getLogoutType()));
        if (StringUtils.isNotBlank(data.getLogoutUrl())) {
            regSvc.setLogoutUrl(new URL(data.getLogoutUrl()));
        }
        // process the Public Key
        final RegisteredServicePublicKeyEditBean publicKey = data.getPublicKey();
        if (publicKey != null && publicKey.isValid()) {
            regSvc.setPublicKey(new RegisteredServicePublicKeyImpl(publicKey.getLocation(), publicKey.getAlgorithm()));
        }
        final Set<RegisteredServiceEditBean.ServiceData.PropertyBean> props = data.getProperties();
        props.forEach(str -> {
            final DefaultRegisteredServiceProperty value = new DefaultRegisteredServiceProperty();
            value.setValues(org.springframework.util.StringUtils.commaDelimitedListToSet(str.getValue()));
            regSvc.getProperties().put(str.getName(), value);
        });
        return regSvc;
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : RegisteredServiceOAuthTypeEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceOAuthTypeEditBean) OAuthRegisteredService(org.apereo.cas.support.oauth.services.OAuthRegisteredService) OidcRegisteredService(org.apereo.cas.services.OidcRegisteredService) RegisteredServicePublicKeyEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServicePublicKeyEditBean) AbstractRegisteredService(org.apereo.cas.services.AbstractRegisteredService) RegisteredServiceEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceEditBean) URL(java.net.URL) RegisteredServiceSamlTypeEditBean(org.apereo.cas.mgmt.services.web.beans.RegisteredServiceSamlTypeEditBean) DefaultRegisteredServiceProperty(org.apereo.cas.services.DefaultRegisteredServiceProperty) RegisteredServicePublicKeyImpl(org.apereo.cas.services.RegisteredServicePublicKeyImpl) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) RegexRegisteredService(org.apereo.cas.services.RegexRegisteredService)

Example 4 with OAuthRegisteredService

use of org.apereo.cas.support.oauth.services.OAuthRegisteredService 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 5 with OAuthRegisteredService

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

Aggregations

OAuthRegisteredService (org.apereo.cas.support.oauth.services.OAuthRegisteredService)81 lombok.val (lombok.val)27 Test (org.junit.Test)25 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)14 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)14 Test (org.junit.jupiter.api.Test)13 ModelAndView (org.springframework.web.servlet.ModelAndView)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 JEEContext (org.pac4j.core.context.JEEContext)8 MockHttpSession (org.springframework.mock.web.MockHttpSession)8 HashMap (java.util.HashMap)7 Service (org.apereo.cas.authentication.principal.Service)7 CasProfile (org.pac4j.cas.profile.CasProfile)7 View (org.springframework.web.servlet.View)7 Principal (org.apereo.cas.authentication.principal.Principal)6 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)6 RedirectView (org.springframework.web.servlet.view.RedirectView)6 Authentication (org.apereo.cas.authentication.Authentication)5 OidcRegisteredService (org.apereo.cas.services.OidcRegisteredService)5 ProfileManager (org.pac4j.core.profile.ProfileManager)5