Search in sources :

Example 11 with AuthorizationRequest

use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project Kustvakt by KorAP.

the class OpenIdAuthorizationService method requestAuthorizationCode.

public URI requestAuthorizationCode(MultivaluedMap<String, String> map, String username, boolean isAuthentication, ZonedDateTime authenticationTime) throws KustvaktException, ParseException {
    AuthorizationCode code = new AuthorizationCode();
    URI redirectUri = null;
    if (isAuthentication) {
        AuthenticationRequest authRequest = null;
        authRequest = AuthenticationRequest.parse((Map<String, List<String>>) map);
        redirectUri = handleAuthenticationRequest(authRequest, code, username, authenticationTime);
        return new AuthenticationSuccessResponse(redirectUri, code, null, null, authRequest.getState(), null, null).toURI();
    } else {
        AuthorizationRequest authzRequest = AuthorizationRequest.parse((Map<String, List<String>>) map);
        redirectUri = handleAuthorizationRequest(authzRequest, code, username, authenticationTime, null);
        return new AuthorizationSuccessResponse(redirectUri, code, null, authzRequest.getState(), null).toURI();
    }
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) List(java.util.List) AuthorizationSuccessResponse(com.nimbusds.oauth2.sdk.AuthorizationSuccessResponse) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) URI(java.net.URI) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse)

Example 12 with AuthorizationRequest

use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project Kustvakt by KorAP.

the class OpenIdAuthorizationService method handleAuthorizationRequest.

private URI handleAuthorizationRequest(AuthorizationRequest authzRequest, AuthorizationCode code, String username, ZonedDateTime authenticationTime, String nonce) throws KustvaktException {
    URI redirectUri = authzRequest.getRedirectionURI();
    String redirectUriStr = (redirectUri != null) ? redirectUri.toString() : null;
    String clientId = authzRequest.getClientID().getValue();
    OAuth2Client client = clientService.authenticateClientId(clientId);
    String verifiedRedirectUri = verifyRedirectUri(client, redirectUriStr);
    try {
        redirectUri = new URI(verifiedRedirectUri);
    } catch (URISyntaxException e) {
        throw new KustvaktException(StatusCodes.INVALID_REDIRECT_URI, "Invalid redirect URI", OAuth2Error.INVALID_REQUEST);
    }
    try {
        ResponseType responseType = authzRequest.getResponseType();
        checkResponseType(responseType.toString());
        Scope scope = authzRequest.getScope();
        Set<String> scopeSet = null;
        if (scope != null) {
            scopeSet = new HashSet<>(scope.toStringList());
        }
        createAuthorization(username, clientId, redirectUriStr, scopeSet, code.getValue(), authenticationTime, nonce);
    } catch (KustvaktException e) {
        e.setRedirectUri(redirectUri);
        throw e;
    }
    return redirectUri;
}
Also used : KustvaktException(de.ids_mannheim.korap.exceptions.KustvaktException) Scope(com.nimbusds.oauth2.sdk.Scope) OAuth2Client(de.ids_mannheim.korap.oauth2.entity.OAuth2Client) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 13 with AuthorizationRequest

use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project OpenConext-oidcng by OpenConext.

the class AuthorizationEndpoint method doAuthorization.

private ModelAndView doAuthorization(MultiValueMap<String, String> parameters, OidcSamlAuthentication samlAuthentication, HttpServletRequest request, boolean consentRequired) throws ParseException, CertificateException, JOSEException, IOException, BadJOSEException, java.text.ParseException, URISyntaxException {
    AuthorizationRequest authenticationRequest = AuthorizationRequest.parse(parameters);
    Scope scope = authenticationRequest.getScope();
    boolean isOpenIdClient = scope != null && isOpenIDRequest(scope.toStringList());
    String clientId = authenticationRequest.getClientID().getValue();
    OpenIDClient client = openIDClientRepository.findOptionalByClientId(clientId).orElseThrow(() -> new UnknownClientException(clientId));
    MDCContext.mdcContext("action", "Authorize", "rp", client.getClientId());
    if (isOpenIdClient) {
        AuthenticationRequest oidcAuthenticationRequest = AuthenticationRequest.parse(parameters);
        if (oidcAuthenticationRequest.specifiesRequestObject()) {
            oidcAuthenticationRequest = JWTRequest.parse(oidcAuthenticationRequest, client);
            LOG.debug("/oidc/authorize with JWT 'request'");
        }
        // swap reference
        authenticationRequest = oidcAuthenticationRequest;
    }
    State state = authenticationRequest.getState();
    String redirectURI = validateRedirectionURI(authenticationRequest.getRedirectionURI(), client).getRedirectURI();
    List<String> scopes = validateScopes(openIDClientRepository, authenticationRequest.getScope(), client);
    ResponseType responseType = validateGrantType(authenticationRequest, client);
    User user = samlAuthentication.getUser();
    MDCContext.mdcContext(user);
    if (scope != null) {
        List<String> scopeList = scope.toStringList();
        boolean apiScopeRequested = !(scopeList.size() == 0 || (scopeList.size() == 1 && scopeList.contains("openid")));
        Set<String> filteredScopes = scopeList.stream().filter(s -> !s.equalsIgnoreCase("openid")).map(String::toLowerCase).collect(toSet());
        List<OpenIDClient> resourceServers = openIDClientRepository.findByScopes_NameIn(filteredScopes);
        Prompt prompt = authenticationRequest.getPrompt();
        boolean consentFromPrompt = prompt != null && prompt.toStringList().contains("consent");
        /*
             * We prompt for consent when the following conditions are met:
             *   Consent feature toggle is on
             *   The RP has requested scope(s) other then openid
             *   Manage attribute "oidc:consentRequired" is true for the RP or the RP has explicitly asked for consent
             *   There is at least one ResourceServer that has the requested scope(s) configured in manage
             */
        if (consentRequired && apiScopeRequested && (consentFromPrompt || client.isConsentRequired()) && resourceServers.size() > 0) {
            LOG.info("Asking for consent for User " + user + " and scopes " + scopes);
            return doConsent(parameters, client, filteredScopes, resourceServers);
        }
    }
    // We do not provide SSO as does EB not - up to the identity provider
    logout(request);
    ResponseMode responseMode = authenticationRequest.impliedResponseMode();
    if (responseType.impliesCodeFlow()) {
        AuthorizationCode authorizationCode = createAndSaveAuthorizationCode(authenticationRequest, client, user);
        LOG.debug(String.format("Returning authorizationCode flow %s %s", ResponseMode.FORM_POST, redirectURI));
        if (responseMode.equals(ResponseMode.FORM_POST)) {
            Map<String, String> body = new HashMap<>();
            body.put("redirect_uri", redirectURI);
            body.put("code", authorizationCode.getCode());
            if (state != null && StringUtils.hasText(state.getValue())) {
                body.put("state", state.getValue());
            }
            return new ModelAndView("form_post", body);
        }
        return new ModelAndView(new RedirectView(authorizationRedirect(redirectURI, state, authorizationCode.getCode(), responseMode.equals(ResponseMode.FRAGMENT))));
    } else if (responseType.impliesImplicitFlow() || responseType.impliesHybridFlow()) {
        if (responseType.impliesImplicitFlow()) {
            // User information is encrypted in access token
            LOG.debug("Deleting user " + user.getSub());
            userRepository.delete(user);
        }
        Map<String, Object> body = authorizationEndpointResponse(user, client, authenticationRequest, scopes, responseType, state);
        LOG.debug(String.format("Returning implicit flow %s %s", ResponseMode.FORM_POST, redirectURI));
        if (responseMode.equals(ResponseMode.FORM_POST)) {
            body.put("redirect_uri", redirectURI);
            return new ModelAndView("form_post", body);
        }
        if (responseMode.equals(ResponseMode.QUERY)) {
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectURI);
            body.forEach(builder::queryParam);
            return new ModelAndView(new RedirectView(builder.toUriString()));
        }
        if (responseMode.equals(ResponseMode.FRAGMENT)) {
            UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectURI);
            String fragment = body.entrySet().stream().map(entry -> String.format("%s=%s", entry.getKey(), entry.getValue())).collect(Collectors.joining("&"));
            builder.fragment(fragment);
            return new ModelAndView(new RedirectView(builder.toUriString()));
        }
        throw new IllegalArgumentException("Response mode " + responseMode + " not supported");
    }
    throw new IllegalArgumentException("Not yet implemented response_type: " + responseType.toString());
}
Also used : AuthorizationCode(oidc.model.AuthorizationCode) AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) User(oidc.model.User) UnknownClientException(oidc.exceptions.UnknownClientException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) OpenIDClient(oidc.model.OpenIDClient) ModelAndView(org.springframework.web.servlet.ModelAndView) ResponseType(com.nimbusds.oauth2.sdk.ResponseType) Scope(com.nimbusds.oauth2.sdk.Scope) ResponseMode(com.nimbusds.oauth2.sdk.ResponseMode) State(com.nimbusds.oauth2.sdk.id.State) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) RedirectView(org.springframework.web.servlet.view.RedirectView) Prompt(com.nimbusds.openid.connect.sdk.Prompt) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 14 with AuthorizationRequest

use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project Application-Gateway by gianlucafrei.

the class Oauth2Driver method startLogin.

@Override
public LoginDriverResult startLogin(URI callbackUri) {
    var settings = getSettings();
    // Preprare Oauth2 request
    URI authzEndpoint = getAuthEndpoint(settings);
    ClientID clientID = getClientId(settings);
    Scope scope = getScopes(settings);
    // Generate random state string for pairing the response to the request
    State state = new State();
    // Build the request
    AuthorizationRequest request = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), clientID).scope(scope).state(state).redirectionURI(callbackUri).endpointURI(authzEndpoint).build();
    // Use this URI to send the end-user's browser to the server
    URI requestURI = request.toURI();
    return new LoginDriverResult(requestURI, state.toString());
}
Also used : LoginDriverResult(org.owasp.oag.services.login.drivers.LoginDriverResult) State(com.nimbusds.oauth2.sdk.id.State) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) URI(java.net.URI)

Example 15 with AuthorizationRequest

use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project OpenConext-oidcng by OpenConext.

the class AuthorizationEndpointUnitTest method doValidateGrantType.

@SuppressWarnings("unchecked")
private void doValidateGrantType(String clientGrantType, String requestResponseType) throws IOException, ParseException {
    AuthorizationRequest authorizationRequest = authorizationRequest(new FluentMap<String, String>().p("client_id", "http://oidc-rp").p("response_type", requestResponseType));
    OpenIDClient client = openIDClient("http://redirect", "scope", clientGrantType);
    ResponseType responseType = AuthorizationEndpoint.validateGrantType(authorizationRequest, client);
    assertTrue(responseType.impliesCodeFlow());
}
Also used : AuthorizationRequest(com.nimbusds.oauth2.sdk.AuthorizationRequest) OpenIDClient(oidc.model.OpenIDClient) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Aggregations

AuthorizationRequest (com.nimbusds.oauth2.sdk.AuthorizationRequest)13 Scope (com.nimbusds.oauth2.sdk.Scope)9 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)7 URI (java.net.URI)6 OpenIDClient (oidc.model.OpenIDClient)6 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)5 State (com.nimbusds.oauth2.sdk.id.State)4 ParseException (com.nimbusds.oauth2.sdk.ParseException)3 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)3 Nonce (com.nimbusds.openid.connect.sdk.Nonce)3 Prompt (com.nimbusds.openid.connect.sdk.Prompt)3 Map (java.util.Map)3 ProvidedRedirectURI (oidc.model.ProvidedRedirectURI)3 OpenIDClientRepository (oidc.repository.OpenIDClientRepository)3 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)3 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)2 IOException (java.io.IOException)2 URISyntaxException (java.net.URISyntaxException)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2