Search in sources :

Example 11 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-security-oauth by spring-projects.

the class AuthorizationEndpoint method append.

private String append(String base, Map<String, ?> query, Map<String, String> keys, boolean fragment) {
    UriComponentsBuilder template = UriComponentsBuilder.newInstance();
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(base);
    URI redirectUri;
    try {
        // assume it's encoded to start with (if it came in over the wire)
        redirectUri = builder.build(true).toUri();
    } catch (Exception e) {
        // ... but allow client registrations to contain hard-coded non-encoded values
        redirectUri = builder.build().toUri();
        builder = UriComponentsBuilder.fromUri(redirectUri);
    }
    template.scheme(redirectUri.getScheme()).port(redirectUri.getPort()).host(redirectUri.getHost()).userInfo(redirectUri.getUserInfo()).path(redirectUri.getPath());
    if (fragment) {
        StringBuilder values = new StringBuilder();
        if (redirectUri.getFragment() != null) {
            String append = redirectUri.getFragment();
            values.append(append);
        }
        for (String key : query.keySet()) {
            if (values.length() > 0) {
                values.append("&");
            }
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            values.append(name + "={" + key + "}");
        }
        if (values.length() > 0) {
            template.fragment(values.toString());
        }
        UriComponents encoded = template.build().expand(query).encode();
        builder.fragment(encoded.getFragment());
    } else {
        for (String key : query.keySet()) {
            String name = key;
            if (keys != null && keys.containsKey(key)) {
                name = keys.get(key);
            }
            template.queryParam(name, "{" + key + "}");
        }
        template.fragment(redirectUri.getFragment());
        UriComponents encoded = template.build().expand(query).encode();
        builder.query(encoded.getQuery());
    }
    return builder.build().toUriString();
}
Also used : UriComponents(org.springframework.web.util.UriComponents) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) URI(java.net.URI) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) UserDeniedAuthorizationException(org.springframework.security.oauth2.common.exceptions.UserDeniedAuthorizationException) RedirectMismatchException(org.springframework.security.oauth2.common.exceptions.RedirectMismatchException) AuthenticationException(org.springframework.security.core.AuthenticationException) BadClientCredentialsException(org.springframework.security.oauth2.common.exceptions.BadClientCredentialsException) HttpSessionRequiredException(org.springframework.web.HttpSessionRequiredException) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) UnsupportedResponseTypeException(org.springframework.security.oauth2.common.exceptions.UnsupportedResponseTypeException) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException) ClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.ClientAuthenticationException) InvalidClientException(org.springframework.security.oauth2.common.exceptions.InvalidClientException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) UnapprovedClientAuthenticationException(org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException)

Example 12 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-security-oauth by spring-projects.

the class ResourceBeanDefinitionParser method doParse.

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    String id = element.getAttribute("id");
    if (!StringUtils.hasText(id)) {
        parserContext.getReaderContext().error("An id must be supplied on a resource element.", element);
    }
    builder.addPropertyValue("id", id);
    String type = element.getAttribute("type");
    if (!StringUtils.hasText(type)) {
        type = "client_credentials";
    }
    builder.addPropertyValue("grantType", type);
    String accessTokenUri = element.getAttribute("access-token-uri");
    if (!StringUtils.hasText(accessTokenUri) && !"implicit".equals(type)) {
        parserContext.getReaderContext().error("An accessTokenUri must be supplied on a resource element of type " + type, element);
    }
    builder.addPropertyValue("accessTokenUri", accessTokenUri);
    String clientId = element.getAttribute("client-id");
    if (!StringUtils.hasText(clientId)) {
        parserContext.getReaderContext().error("An clientId must be supplied on a resource element", element);
    }
    builder.addPropertyValue("clientId", clientId);
    String clientSecret = element.getAttribute("client-secret");
    if (StringUtils.hasText(clientSecret)) {
        builder.addPropertyValue("clientSecret", clientSecret);
    }
    String clientAuthenticationScheme = element.getAttribute("client-authentication-scheme");
    if (StringUtils.hasText(clientAuthenticationScheme)) {
        builder.addPropertyValue("clientAuthenticationScheme", clientAuthenticationScheme);
    }
    String userAuthorizationUri = element.getAttribute("user-authorization-uri");
    if (StringUtils.hasText(userAuthorizationUri)) {
        if (needsUserAuthorizationUri(type)) {
            builder.addPropertyValue("userAuthorizationUri", userAuthorizationUri);
        } else {
            parserContext.getReaderContext().error("The " + type + " grant type does not accept an authorization URI", element);
        }
    } else {
        if (needsUserAuthorizationUri(type)) {
            parserContext.getReaderContext().error("An authorization URI must be supplied for a resource of type " + type, element);
        }
    }
    String preEstablishedRedirectUri = element.getAttribute("pre-established-redirect-uri");
    if (StringUtils.hasText(preEstablishedRedirectUri)) {
        builder.addPropertyValue("preEstablishedRedirectUri", preEstablishedRedirectUri);
    }
    String requireImmediateAuthorization = element.getAttribute("require-immediate-authorization");
    if (StringUtils.hasText(requireImmediateAuthorization)) {
        builder.addPropertyValue("requireImmediateAuthorization", requireImmediateAuthorization);
    }
    String useCurrentUri = element.getAttribute("use-current-uri");
    if (StringUtils.hasText(useCurrentUri)) {
        builder.addPropertyValue("useCurrentUri", useCurrentUri);
    }
    String scope = element.getAttribute("scope");
    if (StringUtils.hasText(scope)) {
        BeanDefinitionBuilder scopesBuilder = BeanDefinitionBuilder.genericBeanDefinition(StringListFactoryBean.class);
        scopesBuilder.addConstructorArgValue(new TypedStringValue(scope));
        builder.addPropertyValue("scope", scopesBuilder.getBeanDefinition());
    }
    AuthenticationScheme btm = AuthenticationScheme.header;
    String bearerTokenMethod = element.getAttribute("authentication-scheme");
    if (StringUtils.hasText(bearerTokenMethod)) {
        btm = AuthenticationScheme.valueOf(bearerTokenMethod);
    }
    builder.addPropertyValue("authenticationScheme", btm);
    String bearerTokenName = element.getAttribute("token-name");
    if (!StringUtils.hasText(bearerTokenName)) {
        bearerTokenName = OAuth2AccessToken.ACCESS_TOKEN;
    }
    builder.addPropertyValue("tokenName", bearerTokenName);
    if (type.equals("password")) {
        String[] attributeNames = { "username", "password" };
        for (String attributeName : attributeNames) {
            String attribute = element.getAttribute(attributeName);
            if (StringUtils.hasText(attribute)) {
                builder.addPropertyValue(attributeName, attribute);
            } else {
                parserContext.getReaderContext().error("A " + attributeName + " must be supplied on a resource element of type " + type, element);
            }
        }
    }
}
Also used : AuthenticationScheme(org.springframework.security.oauth2.common.AuthenticationScheme) BeanDefinitionBuilder(org.springframework.beans.factory.support.BeanDefinitionBuilder) TypedStringValue(org.springframework.beans.factory.config.TypedStringValue)

Example 13 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-security-oauth by spring-projects.

the class ApprovalStoreUserApprovalHandler method checkForPreApproval.

public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    String clientId = authorizationRequest.getClientId();
    Collection<String> requestedScopes = authorizationRequest.getScope();
    Set<String> approvedScopes = new HashSet<String>();
    Set<String> validUserApprovedScopes = new HashSet<String>();
    if (clientDetailsService != null) {
        try {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            for (String scope : requestedScopes) {
                if (client.isAutoApprove(scope)) {
                    approvedScopes.add(scope);
                }
            }
            if (approvedScopes.containsAll(requestedScopes)) {
                // gh-877 - if all scopes are auto approved, approvals still need to be added to the approval store.
                Set<Approval> approvals = new HashSet<Approval>();
                Date expiry = computeExpiry();
                for (String approvedScope : approvedScopes) {
                    approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), approvedScope, expiry, ApprovalStatus.APPROVED));
                }
                approvalStore.addApprovals(approvals);
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client");
        }
    }
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up user approved authorizations for ");
        builder.append("client_id=" + clientId);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }
    // Find the stored approvals for that user and client
    Collection<Approval> userApprovals = approvalStore.getApprovals(userAuthentication.getName(), clientId);
    // Look at the scopes and see if they have expired
    Date today = new Date();
    for (Approval approval : userApprovals) {
        if (approval.getExpiresAt().after(today)) {
            if (approval.getStatus() == ApprovalStatus.APPROVED) {
                validUserApprovedScopes.add(approval.getScope());
                approvedScopes.add(approval.getScope());
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Valid user approved/denied scopes are " + validUserApprovedScopes);
    }
    // this request is approved
    if (validUserApprovedScopes.containsAll(requestedScopes)) {
        approvedScopes.retainAll(requestedScopes);
        // Set only the scopes that have been approved by the user
        authorizationRequest.setScope(approvedScopes);
        authorizationRequest.setApproved(true);
    }
    return authorizationRequest;
}
Also used : ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException) Date(java.util.Date) HashSet(java.util.HashSet)

Example 14 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-security-oauth by spring-projects.

the class TokenStoreUserApprovalHandler method checkForPreApproval.

@Override
public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) {
    boolean approved = false;
    String clientId = authorizationRequest.getClientId();
    Set<String> scopes = authorizationRequest.getScope();
    if (clientDetailsService != null) {
        try {
            ClientDetails client = clientDetailsService.loadClientByClientId(clientId);
            approved = true;
            for (String scope : scopes) {
                if (!client.isAutoApprove(scope)) {
                    approved = false;
                }
            }
            if (approved) {
                authorizationRequest.setApproved(true);
                return authorizationRequest;
            }
        } catch (ClientRegistrationException e) {
            logger.warn("Client registration problem prevent autoapproval check for client=" + clientId);
        }
    }
    OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest);
    OAuth2Authentication authentication = new OAuth2Authentication(storedOAuth2Request, userAuthentication);
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Looking up existing token for ");
        builder.append("client_id=" + clientId);
        builder.append(", scope=" + scopes);
        builder.append(" and username=" + userAuthentication.getName());
        logger.debug(builder.toString());
    }
    OAuth2AccessToken accessToken = tokenStore.getAccessToken(authentication);
    if (logger.isDebugEnabled()) {
        logger.debug("Existing access token=" + accessToken);
    }
    if (accessToken != null && !accessToken.isExpired()) {
        if (logger.isDebugEnabled()) {
            logger.debug("User already approved with token=" + accessToken);
        }
        // A token was already granted and is still valid, so this is already approved
        approved = true;
    } else {
        logger.debug("Checking explicit approval");
        approved = userAuthentication.isAuthenticated() && approved;
    }
    authorizationRequest.setApproved(approved);
    return authorizationRequest;
}
Also used : OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ClientRegistrationException(org.springframework.security.oauth2.provider.ClientRegistrationException)

Example 15 with Builder

use of org.springframework.security.oauth2.client.registration.ClientRegistration.Builder in project spring-boot by spring-projects.

the class OAuth2ClientPropertiesRegistrationAdapter method getClientRegistration.

private static ClientRegistration getClientRegistration(String registrationId, OAuth2ClientProperties.Registration properties, Map<String, Provider> providers) {
    Builder builder = getBuilderFromIssuerIfPossible(registrationId, properties.getProvider(), providers);
    if (builder == null) {
        builder = getBuilder(registrationId, properties.getProvider(), providers);
    }
    PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
    map.from(properties::getClientId).to(builder::clientId);
    map.from(properties::getClientSecret).to(builder::clientSecret);
    map.from(properties::getClientAuthenticationMethod).as(ClientAuthenticationMethod::new).to(builder::clientAuthenticationMethod);
    map.from(properties::getAuthorizationGrantType).as(AuthorizationGrantType::new).to(builder::authorizationGrantType);
    map.from(properties::getRedirectUri).to(builder::redirectUri);
    map.from(properties::getScope).as(StringUtils::toStringArray).to(builder::scope);
    map.from(properties::getClientName).to(builder::clientName);
    return builder.build();
}
Also used : Builder(org.springframework.security.oauth2.client.registration.ClientRegistration.Builder) PropertyMapper(org.springframework.boot.context.properties.PropertyMapper)

Aggregations

Test (org.junit.jupiter.api.Test)9 Jwt (org.springframework.security.oauth2.jwt.Jwt)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)6 GrantedAuthority (org.springframework.security.core.GrantedAuthority)5 Authentication (org.springframework.security.core.Authentication)3 Builder (org.springframework.security.oauth2.client.registration.ClientRegistration.Builder)3 ClientRegistrationException (org.springframework.security.oauth2.provider.ClientRegistrationException)3 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)2 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)2 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)2 HashMap (java.util.HashMap)2 Base64Exception (org.apache.cxf.common.util.Base64Exception)2 CommonOAuth2Provider (org.springframework.security.config.oauth2.client.CommonOAuth2Provider)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 OAuth2AuthorizeRequest (org.springframework.security.oauth2.client.OAuth2AuthorizeRequest)2 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)2 UriComponentsBuilder (org.springframework.web.util.UriComponentsBuilder)2 DefaultExceptionMessageBuilder (com.epam.ta.reportportal.commons.exception.message.DefaultExceptionMessageBuilder)1 DefaultErrorResolver (com.epam.ta.reportportal.commons.exception.rest.DefaultErrorResolver)1 ReportPortalExceptionResolver (com.epam.ta.reportportal.commons.exception.rest.ReportPortalExceptionResolver)1