Search in sources :

Example 6 with AuthorizationCode

use of oidc.model.AuthorizationCode 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 7 with AuthorizationCode

use of oidc.model.AuthorizationCode in project OpenConext-oidcng by OpenConext.

the class AuthorizationEndpointTest method hybridFlowFragment.

@Test
public void hybridFlowFragment() throws IOException, BadJOSEException, ParseException, JOSEException {
    Response response = doAuthorize("mock-sp", "code id_token token", null, "nonce", null);
    String url = response.getHeader("Location");
    String fragment = url.substring(url.indexOf("#") + 1);
    Map<String, String> fragmentParameters = fragmentToMap(fragment);
    String code = fragmentParameters.get("code");
    AuthorizationCode authorizationCode = mongoTemplate.findOne(Query.query(Criteria.where("code").is(code)), AuthorizationCode.class);
    User user = mongoTemplate.findOne(Query.query(Criteria.where("sub").is(authorizationCode.getSub())), User.class);
    assertNotNull(user);
    String accessToken = fragmentParameters.get("access_token");
    JWTClaimsSet claimsSet = assertImplicitFlowResponse(fragmentParameters);
    Map<String, Object> tokenResponse = doToken(code);
    List<User> users = mongoTemplate.find(Query.query(Criteria.where("sub").is(authorizationCode.getSub())), User.class);
    assertEquals(0, users.size());
    String newAccessToken = (String) tokenResponse.get("access_token");
    /*
         * If an Access Token is returned from both the Authorization Endpoint and from the Token Endpoint, which is
         * the case for the response_type values code token and code id_token token, their values MAY be the same or
         * they MAY be different. Note that different Access Tokens might be returned be due to the different
         * security characteristics of the two endpoints and the lifetimes and the access to resources granted
         * by them might also be different.
         */
    assertNotEquals(accessToken, newAccessToken);
    String idToken = (String) tokenResponse.get("id_token");
    JWTClaimsSet newClaimsSet = processToken(idToken, port);
    assertEquals(claimsSet.getAudience(), newClaimsSet.getAudience());
    assertEquals(claimsSet.getSubject(), newClaimsSet.getSubject());
    assertEquals(claimsSet.getIssuer(), newClaimsSet.getIssuer());
}
Also used : Response(io.restassured.response.Response) AuthorizationCode(oidc.model.AuthorizationCode) User(oidc.model.User) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) StringContains.containsString(org.hamcrest.core.StringContains.containsString) AbstractIntegrationTest(oidc.AbstractIntegrationTest) Test(org.junit.Test) SignedJWTTest(oidc.secure.SignedJWTTest)

Example 8 with AuthorizationCode

use of oidc.model.AuthorizationCode in project OpenConext-oidcng by OpenConext.

the class AuthorizationCodeRepositoryTest method findByCode.

@Test
public void findByCode() throws URISyntaxException {
    String code = UUID.randomUUID().toString();
    subject.insert(new AuthorizationCode(code, "sub", "clientId", emptyList(), new URI("http://redirectURI"), "codeChallenge", "codeChallengeMethod", "nonce", emptyList(), true, new Date()));
    assertEquals(code, subject.findByCode(code).getCode());
}
Also used : AuthorizationCode(oidc.model.AuthorizationCode) URI(java.net.URI) Date(java.util.Date) Test(org.junit.Test) AbstractIntegrationTest(oidc.AbstractIntegrationTest)

Example 9 with AuthorizationCode

use of oidc.model.AuthorizationCode in project OpenConext-oidcng by OpenConext.

the class AuthorizationCodeRepositoryTest method deleteByExpiresInBefore.

@Test
public void deleteByExpiresInBefore() throws URISyntaxException {
    Date expiresIn = Date.from(LocalDateTime.now().minusDays(1).atZone(ZoneId.systemDefault()).toInstant());
    subject.insert(new AuthorizationCode("code", "sub", "clientId", emptyList(), new URI("http://redirectURI"), "codeChallenge", "codeChallengeMethod", "nonce", emptyList(), true, expiresIn));
    long count = subject.deleteByExpiresInBefore(new Date());
    assertEquals(1L, count);
}
Also used : AuthorizationCode(oidc.model.AuthorizationCode) URI(java.net.URI) Date(java.util.Date) Test(org.junit.Test) AbstractIntegrationTest(oidc.AbstractIntegrationTest)

Example 10 with AuthorizationCode

use of oidc.model.AuthorizationCode in project OpenConext-oidcng by OpenConext.

the class ConcurrentAuthorizationCodeRepositoryTest method findByCodeAndMarkUsed.

@Test
public void findByCodeAndMarkUsed() throws URISyntaxException {
    authorizationCodeRepository.save(new AuthorizationCode("code", "sub", "client_id", Collections.singletonList("openid"), new URI("http://localhost"), null, null, "nonce", null, true, new Date()));
    assertNull(concurrentAuthorizationCodeRepository.findByCodeNotAlreadyUsedAndMarkAsUsed("nope"));
    AuthorizationCode authorizationCode = concurrentAuthorizationCodeRepository.findByCodeNotAlreadyUsedAndMarkAsUsed("code");
    assertTrue(authorizationCode.isAlreadyUsed());
    assertTrue(authorizationCodeRepository.findByCode("code").isAlreadyUsed());
    assertNull(concurrentAuthorizationCodeRepository.findByCodeNotAlreadyUsedAndMarkAsUsed("code"));
}
Also used : AuthorizationCode(oidc.model.AuthorizationCode) URI(java.net.URI) Date(java.util.Date) Test(org.junit.Test) AbstractIntegrationTest(oidc.AbstractIntegrationTest)

Aggregations

AuthorizationCode (oidc.model.AuthorizationCode)10 URI (java.net.URI)6 AbstractIntegrationTest (oidc.AbstractIntegrationTest)6 Test (org.junit.Test)6 Date (java.util.Date)5 User (oidc.model.User)4 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)3 Scope (com.nimbusds.oauth2.sdk.Scope)2 CodeChallenge (com.nimbusds.oauth2.sdk.pkce.CodeChallenge)2 CodeChallengeMethod (com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod)2 LinkedHashMap (java.util.LinkedHashMap)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 AuthorizationRequest (com.nimbusds.oauth2.sdk.AuthorizationRequest)1 ResponseMode (com.nimbusds.oauth2.sdk.ResponseMode)1 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)1 State (com.nimbusds.oauth2.sdk.id.State)1 CodeVerifier (com.nimbusds.oauth2.sdk.pkce.CodeVerifier)1 Nonce (com.nimbusds.openid.connect.sdk.Nonce)1 Prompt (com.nimbusds.openid.connect.sdk.Prompt)1 Response (io.restassured.response.Response)1