Search in sources :

Example 6 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project OpenConext-oidcng by OpenConext.

the class JWTRequestTest method fullBlown.

@Test
public void fullBlown() throws Exception {
    OpenIDClient client = getClient();
    setCertificateFields(client, getStrippedCertificate(), null, null);
    String keyID = getCertificateKeyID(client);
    SignedJWT signedJWT = signedJWT(client.getClientId(), keyID, client.getRedirectUrls().get(0));
    ClaimsRequest claimsRequest = new ClaimsRequest();
    claimsRequest.addIDTokenClaim("email");
    List<LangTag> langTags = Collections.singletonList(new LangTag("en"));
    List<ACR> acrValues = Collections.singletonList(new ACR("loa"));
    AuthenticationRequest authenticationRequest = new AuthenticationRequest(new URI("http://localhost/authorize"), ResponseType.getDefault(), ResponseMode.FRAGMENT, new Scope("openid"), new ClientID(client.getClientId()), new URI(client.getRedirectUrls().get(0)), new State("state"), new Nonce("nonce"), Display.getDefault(), Prompt.parse("consent"), 1200, langTags, langTags, null, "hint", acrValues, claimsRequest, "purpose", signedJWT, null, CodeChallenge.compute(CodeChallengeMethod.S256, new CodeVerifier()), CodeChallengeMethod.S256, Collections.singletonList(new URI("http://localhost")), true, Collections.singletonMap("custom", Collections.singletonList("value")));
    authenticationRequest = JWTRequest.parse(authenticationRequest, client);
    assertEquals("login", authenticationRequest.getPrompt().toString());
}
Also used : OpenIDClient(oidc.model.OpenIDClient) SignedJWT(com.nimbusds.jwt.SignedJWT) ClaimsRequest(com.nimbusds.openid.connect.sdk.ClaimsRequest) URI(java.net.URI) ACR(com.nimbusds.openid.connect.sdk.claims.ACR) Nonce(com.nimbusds.openid.connect.sdk.Nonce) LangTag(com.nimbusds.langtag.LangTag) CodeVerifier(com.nimbusds.oauth2.sdk.pkce.CodeVerifier) Scope(com.nimbusds.oauth2.sdk.Scope) State(com.nimbusds.oauth2.sdk.id.State) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) Test(org.junit.Test)

Example 7 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project obiba-commons by obiba.

the class OIDCLoginFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    J2EContext context = new J2EContext(request, response);
    String provider = OIDCHelper.extractProviderName(context, providerParameter);
    if (Strings.isNullOrEmpty(provider)) {
        log.error("No ID provider could be identified.");
    } else {
        try {
            OIDCConfiguration config = oidcConfigurationProvider.getConfiguration(provider);
            if (config == null)
                throw new OIDCException("No OIDC configuration could be found: " + provider);
            OIDCAuthenticationRequestFactory factory = new OIDCAuthenticationRequestFactory(makeCallbackURL(provider));
            AuthenticationRequest authRequest = factory.create(config);
            if (oidcSessionManager != null) {
                OIDCSession session = makeSession(context, authRequest);
                oidcSessionManager.saveSession(session);
            }
            response.sendRedirect(authRequest.toURI().toString());
        } catch (OIDCException e) {
            log.error("OIDC login request to '{}' failed.", provider, e);
            throw e;
        }
    }
    filterChain.doFilter(request, response);
}
Also used : J2EContext(org.obiba.oidc.web.J2EContext) OIDCAuthenticationRequestFactory(org.obiba.oidc.utils.OIDCAuthenticationRequestFactory) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest)

Example 8 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project java-oauth-server by authlete.

the class Federation method buildAuthenticationRequest.

// ------------------------------------------------------------
// Authentication Request
// ------------------------------------------------------------
private AuthenticationRequest buildAuthenticationRequest(State state, CodeVerifier verifier, CodeChallengeMethod method) throws IOException {
    // The authorization endpoint of the OpenID provider.
    URI endpoint = authorizationEndpoint();
    // response_type
    ResponseType responseType = new ResponseType("code");
    // scope
    Scope scope = buildAuthenticationRequestScope();
    // client_id (from federation configuration)
    ClientID clientId = clientId();
    // redirect_uri (from federation configuration)
    URI redirectUri = redirectUri();
    // Start to build an authentication request.
    AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(responseType, scope, clientId, redirectUri).endpointURI(endpoint);
    // state
    if (state != null) {
        builder.state(state);
    }
    // code_challenge & code_challenge_method
    if (verifier != null && method != null) {
        // code_challenge is computed from the verifier and the method.
        builder.codeChallenge(verifier, method);
    }
    return builder.build();
}
Also used : Scope(com.nimbusds.oauth2.sdk.Scope) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) URI(java.net.URI) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 9 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project java-oauth-server by authlete.

the class Federation method createFederationRequest.

// ------------------------------------------------------------
// Federation Flow
// ------------------------------------------------------------
/**
 * Create an authentication request that is to be sent to the authorization
 * endpoint of the OpenID Provider.
 */
public URI createFederationRequest(String state, String codeVerifier) throws IOException {
    // state
    State st = (state != null) ? new State(state) : null;
    // Code verifier that is to be used to calculate code_challenge.
    CodeVerifier verifier = (codeVerifier != null) ? new CodeVerifier(codeVerifier) : null;
    // code_challenge_method
    CodeChallengeMethod method = (verifier != null) ? CodeChallengeMethod.S256 : null;
    // Create an authentication request that is to be sent to
    // the authorization endpoint.
    AuthenticationRequest request = buildAuthenticationRequest(st, verifier, method);
    return request.toURI();
}
Also used : CodeVerifier(com.nimbusds.oauth2.sdk.pkce.CodeVerifier) CodeChallengeMethod(com.nimbusds.oauth2.sdk.pkce.CodeChallengeMethod) State(com.nimbusds.oauth2.sdk.id.State) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest)

Example 10 with AuthenticationRequest

use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-authentication-api by alphagov.

the class AuthorisationHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        var persistentSessionId = authorizationService.getExistingOrCreateNewPersistentSessionId(input.getHeaders());
        var ipAddress = IpAddressHelper.extractIpAddress(input);
        auditService.submitAuditEvent(OidcAuditableEvent.AUTHORISATION_REQUEST_RECEIVED, context.getAwsRequestId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, persistentSessionId);
        attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentSessionId);
        attachLogFieldToLogs(AWS_REQUEST_ID, context.getAwsRequestId());
        LOG.info("Received authentication request");
        Map<String, List<String>> queryStringParameters;
        AuthenticationRequest authRequest;
        try {
            queryStringParameters = input.getQueryStringParameters().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> List.of(entry.getValue())));
            authRequest = AuthenticationRequest.parse(queryStringParameters);
        } catch (ParseException e) {
            if (e.getRedirectionURI() == null) {
                LOG.warn("Authentication request could not be parsed: redirect URI or Client ID is missing from auth request");
                throw new RuntimeException("Redirect URI or ClientID is missing from auth request", e);
            }
            LOG.warn("Authentication request could not be parsed", e);
            return generateErrorResponse(e.getRedirectionURI(), e.getState(), e.getResponseMode(), e.getErrorObject(), context, ipAddress, persistentSessionId);
        } catch (NullPointerException e) {
            LOG.warn("No query string parameters are present in the Authentication request", e);
            throw new RuntimeException("No query string parameters are present in the Authentication request", e);
        }
        var error = authorizationService.validateAuthRequest(authRequest);
        return error.map(e -> generateErrorResponse(authRequest.getRedirectionURI(), authRequest.getState(), authRequest.getResponseMode(), e, context, ipAddress, persistentSessionId)).orElseGet(() -> getOrCreateSessionAndRedirect(queryStringParameters, sessionService.getSessionFromSessionCookie(input.getHeaders()), authRequest, context, ipAddress, persistentSessionId));
    });
}
Also used : Prompt(com.nimbusds.openid.connect.sdk.Prompt) SessionService(uk.gov.di.authentication.shared.services.SessionService) URISyntaxException(java.net.URISyntaxException) LocalDateTime(java.time.LocalDateTime) Context(com.amazonaws.services.lambda.runtime.Context) ConfigurationService(uk.gov.di.authentication.shared.services.ConfigurationService) RequestHandler(com.amazonaws.services.lambda.runtime.RequestHandler) ResponseMode(com.nimbusds.oauth2.sdk.ResponseMode) ResponseHeaders(uk.gov.di.authentication.shared.entity.ResponseHeaders) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Session(uk.gov.di.authentication.shared.entity.Session) CLIENT_SESSION_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.CLIENT_SESSION_ID) PERSISTENT_SESSION_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.PERSISTENT_SESSION_ID) Map(java.util.Map) ParseException(com.nimbusds.oauth2.sdk.ParseException) URI(java.net.URI) AWS_REQUEST_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.AWS_REQUEST_ID) CLIENT_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.CLIENT_ID) LogLineHelper.updateAttachedSessionIdToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.updateAttachedSessionIdToLogs) MetadataPair.pair(uk.gov.di.authentication.shared.services.AuditService.MetadataPair.pair) WarmerHelper.isWarming(uk.gov.di.authentication.shared.helpers.WarmerHelper.isWarming) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) OIDCError(com.nimbusds.openid.connect.sdk.OIDCError) URIBuilder(org.apache.http.client.utils.URIBuilder) OidcAuditableEvent(uk.gov.di.authentication.oidc.domain.OidcAuditableEvent) IpAddressHelper(uk.gov.di.authentication.shared.helpers.IpAddressHelper) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) AuditService(uk.gov.di.authentication.shared.services.AuditService) LogLineHelper.attachLogFieldToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.attachLogFieldToLogs) State(com.nimbusds.oauth2.sdk.id.State) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) CookieHelper(uk.gov.di.authentication.shared.helpers.CookieHelper) Collectors(java.util.stream.Collectors) AuthorizationService(uk.gov.di.authentication.shared.services.AuthorizationService) ClientSessionService(uk.gov.di.authentication.shared.services.ClientSessionService) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) LogLineHelper.attachSessionIdToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.attachSessionIdToLogs) LogLineHelper.updateAttachedLogFieldToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.updateAttachedLogFieldToLogs) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) List(java.util.List) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest)

Aggregations

AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)73 Scope (com.nimbusds.oauth2.sdk.Scope)44 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)34 State (com.nimbusds.oauth2.sdk.id.State)29 Nonce (com.nimbusds.openid.connect.sdk.Nonce)27 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)24 Test (org.junit.jupiter.api.Test)19 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)16 URI (java.net.URI)16 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)12 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)11 VectorOfTrust (uk.gov.di.authentication.shared.entity.VectorOfTrust)10 AuthenticationSuccessResponse (com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse)8 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)7 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)7 MethodSource (org.junit.jupiter.params.provider.MethodSource)6 SignedJWT (com.nimbusds.jwt.SignedJWT)5 OIDCClaimsRequest (com.nimbusds.openid.connect.sdk.OIDCClaimsRequest)5 HashMap (java.util.HashMap)5