use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project di-ipv-cri-uk-passport-back by alphagov.
the class AuthorizationCodeHandler method handleRequest.
@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
Map<String, List<String>> queryStringParameters = getQueryStringParametersAsMap(input);
String userId = RequestHelper.getHeaderByKey(input.getHeaders(), "user_id");
try {
var validationResult = authRequestValidator.validateRequest(queryStringParameters, userId);
if (validationResult.isPresent()) {
return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, validationResult.get());
}
AuthenticationRequest authenticationRequest = AuthenticationRequest.parse(queryStringParameters);
PassportAttributes passportAttributes = parsePassportFormRequest(input.getBody());
JWSObject preparedDcsPayload = preparePayload(passportAttributes);
DcsSignedEncryptedResponse dcsResponse = doPassportCheck(preparedDcsPayload);
auditService.sendAuditEvent(AuditEventTypes.PASSPORT_REQUEST_SENT_TO_DCS);
DcsResponse unwrappedDcsResponse = unwrapDcsResponse(dcsResponse);
passportAttributes.setDcsResponse(unwrappedDcsResponse);
validateDcsResponse(unwrappedDcsResponse);
PassportCheckDao passportCheckDao = new PassportCheckDao(UUID.randomUUID().toString(), passportAttributes, generateGpg45Score(unwrappedDcsResponse), userId);
passportService.persistDcsResponse(passportCheckDao);
AuthorizationCode authorizationCode = authorizationCodeService.generateAuthorizationCode();
authorizationCodeService.persistAuthorizationCode(authorizationCode.getValue(), passportCheckDao.getResourceId(), authenticationRequest.getRedirectionURI().toString());
return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_OK, Map.of(AUTHORIZATION_CODE, authorizationCode));
} catch (HttpResponseExceptionWithErrorBody e) {
return ApiGatewayResponseGenerator.proxyJsonResponse(e.getStatusCode(), e.getErrorBody());
} catch (ParseException e) {
LOGGER.error("Authentication request could not be parsed", e);
return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, ErrorResponse.FAILED_TO_PARSE_OAUTH_QUERY_STRING_PARAMETERS);
} catch (SqsException e) {
LOGGER.error("Failed to send audit event to SQS queue because: {}", e.getMessage());
return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, ErrorResponse.FAILED_TO_SEND_AUDIT_MESSAGE_TO_SQS_QUEUE);
}
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest 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());
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project OpenConext-oidcng by OpenConext.
the class OidcEndpoint method getClaims.
default List<String> getClaims(AuthorizationRequest authorizationRequest) {
List<String> idTokenClaims = new ArrayList<>();
if (isOpenIDRequest(authorizationRequest)) {
AuthenticationRequest authenticationRequest = (AuthenticationRequest) authorizationRequest;
ClaimsRequest claimsRequest = authenticationRequest.getClaims();
if (claimsRequest != null) {
idTokenClaims.addAll(claimsRequest.getIDTokenClaims().stream().map(entry -> entry.getClaimName()).collect(Collectors.toList()));
}
}
return idTokenClaims;
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project Application-Gateway by gianlucafrei.
the class LoginLogoutTest method testLoginGetRedirectUrl.
@Test
void testLoginGetRedirectUrl() throws Exception {
// TWO Step test
// ACT1: Start the login
var loginResult = webClient.get().uri("/auth/local/login").exchange().expectStatus().isFound().returnResult(String.class);
var redirectUriString = loginResult.getResponseHeaders().getFirst("Location");
URI redirectUri = new URI(redirectUriString);
AuthenticationRequest oidcRequest = AuthenticationRequest.parse(redirectUri);
LoginProvider provider = mainConfig.getLoginProviders().get("local");
assertTrue(redirectUriString.startsWith((String) provider.getWith().get("authEndpoint")));
assertEquals(provider.getWith().get("clientId"), oidcRequest.getClientID().toString());
var loginStateCookie = loginResult.getResponseCookies().getFirst(LoginStateCookie.NAME);
// ACT 2: Call the callback url
// Arrange
String authorizationResponse = String.format("?state=%s&code=%s", oidcRequest.getState().getValue(), "authCode");
var callbackResult = webClient.get().uri("/auth/local/callback" + authorizationResponse).cookie(loginStateCookie.getName(), loginStateCookie.getValue()).exchange().expectStatus().isFound().returnResult(String.class);
var sessionCookie = callbackResult.getResponseCookies().getFirst(LoginCookie.NAME);
var csrfCookie = callbackResult.getResponseCookies().getFirst(CsrfCookie.NAME);
// ACT 3: Call the session endpoint
webClient.get().uri("/auth/session").cookie(sessionCookie.getName(), sessionCookie.getValue()).exchange().expectStatus().isOk().expectBody().jsonPath("$.state").isEqualTo(SessionInformation.SESSION_STATE_AUTHENTICATED);
// ACT 4: Logout
var logoutResult = webClient.get().uri("/auth/logout").cookie(sessionCookie.getName(), sessionCookie.getValue()).cookie(csrfCookie.getName(), csrfCookie.getValue()).exchange().expectStatus().isFound().returnResult(String.class);
// Expect that the cookie is deleted
var sessionCookie2 = logoutResult.getResponseCookies().getFirst(LoginCookie.NAME);
assertEquals(0, sessionCookie2.getMaxAge().getSeconds());
assertEquals(sessionCookie.getName(), sessionCookie2.getName());
assertEquals(sessionCookie.getPath(), sessionCookie2.getPath());
assertEquals(sessionCookie.getDomain(), sessionCookie2.getDomain());
}
use of com.nimbusds.openid.connect.sdk.AuthenticationRequest in project OpenConext-oidcng by OpenConext.
the class JWTRequestTest method parseWithRequestUrl.
@Test
public void parseWithRequestUrl() throws Exception {
OpenIDClient client = getClient();
String keyID = getCertificateKeyID(client);
SignedJWT signedJWT = signedJWT(client.getClientId(), keyID, client.getRedirectUrls().get(0));
stubFor(get(urlPathMatching("/request")).willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(signedJWT.serialize())));
AuthenticationRequest authenticationRequest = new AuthenticationRequest.Builder(ResponseType.getDefault(), new Scope("openid"), new ClientID(client.getClientId()), new URI("http://localhost:8080")).requestURI(new URI("http://localhost:8089/request")).build();
callParse(client, authenticationRequest);
}
Aggregations