use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project di-authentication-api by alphagov.
the class TokenHandlerTest method generateRequestObjectAuthRequest.
private static AuthorizationRequest generateRequestObjectAuthRequest() throws JOSEException {
var keyPair = KeyPairHelper.GENERATE_RSA_KEY_PAIR();
Scope scope = new Scope(DOC_CHECKING_APP, OIDCScopeValue.OPENID);
var jwtClaimsSet = new JWTClaimsSet.Builder().audience(AUDIENCE).claim("redirect_uri", REDIRECT_URI).claim("response_type", ResponseType.CODE.toString()).claim("scope", scope.toString()).claim("client_id", DOC_APP_CLIENT_ID.getValue()).claim("state", STATE.getValue()).issuer(CLIENT_ID).build();
var signedJWT = generateSignedJWT(jwtClaimsSet, keyPair);
return generateAuthRequest(signedJWT);
}
use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project di-authentication-api by alphagov.
the class TokenHandlerTest method shouldReturn200ForSuccessfulDocAppJourneyTokenRequest.
@Test
void shouldReturn200ForSuccessfulDocAppJourneyTokenRequest() throws JOSEException {
KeyPair keyPair = generateRsaKeyPair();
UserProfile userProfile = generateUserProfile();
SignedJWT signedJWT = generateIDToken(DOC_APP_CLIENT_ID.getValue(), PUBLIC_SUBJECT, "issuer-url", new ECKeyGenerator(Curve.P_256).algorithm(JWSAlgorithm.ES256).generate());
OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(signedJWT, accessToken, refreshToken));
PrivateKeyJWT privateKeyJWT = generatePrivateKeyJWT(keyPair.getPrivate());
ClientRegistry clientRegistry = generateClientRegistry(keyPair, false);
when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
when(clientService.getClient(DOC_APP_CLIENT_ID.getValue())).thenReturn(Optional.of(clientRegistry));
when(tokenService.getClientIDFromPrivateKeyJWT(anyString())).thenReturn(Optional.of(DOC_APP_CLIENT_ID.getValue()));
when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(DOC_APP_CLIENT_ID.getValue()))).thenReturn(Optional.empty());
String authCode = new AuthorizationCode().toString();
AuthorizationRequest authenticationRequest = generateRequestObjectAuthRequest();
VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
ClientSession clientSession = new ClientSession(authenticationRequest.toParameters(), LocalDateTime.now(), vtr);
clientSession.setDocAppSubjectId(DOC_APP_USER_PUBLIC_SUBJECT);
when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID).setClientSession(clientSession)));
when(dynamoService.getUserProfileByEmail(TEST_EMAIL)).thenReturn(userProfile);
when(tokenService.generateTokenResponse(DOC_APP_CLIENT_ID.getValue(), DOC_APP_USER_PUBLIC_SUBJECT, new Scope(OIDCScopeValue.OPENID, DOC_CHECKING_APP), Map.of(), DOC_APP_USER_PUBLIC_SUBJECT, vtr.retrieveVectorOfTrustForToken(), null, false, null, true)).thenReturn(tokenResponse);
APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode, DOC_APP_CLIENT_ID.getValue(), true);
assertThat(result, hasStatus(200));
assertTrue(result.getBody().contains(refreshToken.getValue()));
assertTrue(result.getBody().contains(accessToken.getValue()));
}
use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project di-authentication-api by alphagov.
the class UpdateProfileHandler method handleRequestWithUserContext.
@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, UpdateProfileRequest request, UserContext userContext) {
Session session = userContext.getSession();
String persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
LogLineHelper.attachSessionIdToLogs(session);
attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentSessionId);
LOG.info("Processing request");
String ipAddress = IpAddressHelper.extractIpAddress(input);
if (!session.validateSession(request.getEmail())) {
LOG.info("Invalid session");
return generateErrorResponse(ErrorResponse.ERROR_1000, context);
}
AuditableEvent auditableEvent;
String auditablePhoneNumber = userContext.getUserProfile().map(UserProfile::getPhoneNumber).orElse(AuditService.UNKNOWN);
String auditableClientId = userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN);
switch(request.getUpdateProfileType()) {
case ADD_PHONE_NUMBER:
{
String phoneNumber = PhoneNumberHelper.removeWhitespaceFromPhoneNumber(request.getProfileInformation());
Optional<ErrorResponse> errorResponse = ValidationHelper.validatePhoneNumber(phoneNumber);
if (errorResponse.isPresent()) {
return generateErrorResponse(errorResponse.get(), context);
}
authenticationService.updatePhoneNumber(request.getEmail(), request.getProfileInformation());
auditableEvent = UPDATE_PROFILE_PHONE_NUMBER;
auditablePhoneNumber = request.getProfileInformation();
LOG.info("Phone number updated");
break;
}
case CAPTURE_CONSENT:
{
ClientSession clientSession = userContext.getClientSession();
if (clientSession == null) {
return generateErrorResponse(ErrorResponse.ERROR_1000, context);
}
AuthenticationRequest authorizationRequest;
try {
authorizationRequest = AuthenticationRequest.parse(clientSession.getAuthRequestParams());
} catch (ParseException e) {
LOG.info("Cannot retrieve auth request params from client session id");
return generateErrorResponse(ErrorResponse.ERROR_1001, context);
}
String clientId = authorizationRequest.getClientID().getValue();
attachLogFieldToLogs(CLIENT_ID, clientId);
Set<String> claimsConsented;
if (!Boolean.parseBoolean(request.getProfileInformation())) {
claimsConsented = OIDCScopeValue.OPENID.getClaimNames();
} else {
claimsConsented = ValidScopes.getClaimsForListOfScopes(authorizationRequest.getScope().toStringList());
}
processAndUpdateClientConsent(request.getEmail(), userContext, clientId, claimsConsented);
auditableEvent = UPDATE_PROFILE_CONSENT_UPDATED;
auditableClientId = clientId;
LOG.info("Consent updated");
break;
}
case UPDATE_TERMS_CONDS:
{
authenticationService.updateTermsAndConditions(request.getEmail(), configurationService.getTermsAndConditionsVersion());
auditableEvent = UPDATE_PROFILE_TERMS_CONDS_ACCEPTANCE;
LOG.info("Updated terms and conditions for Version: {}", configurationService.getTermsAndConditionsVersion());
break;
}
default:
LOG.error("Encountered unexpected error while processing session: {}", session.getSessionId());
return generateErrorResponse(ErrorResponse.ERROR_1013, context);
}
auditService.submitAuditEvent(auditableEvent, context.getAwsRequestId(), session.getSessionId(), auditableClientId, userContext.getUserProfile().map(UserProfile::getSubjectID).orElse(AuditService.UNKNOWN), userContext.getSession().getEmailAddress(), ipAddress, auditablePhoneNumber, persistentSessionId);
return generateEmptySuccessApiGatewayResponse();
}
use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project di-authentication-api by alphagov.
the class StartServiceTest method buildUserContext.
private UserContext buildUserContext(String vtrValue, boolean consentRequired, boolean cookieConsentShared, ClientType clientType, SignedJWT requestObject, boolean identityVerificationSupport, boolean isAuthenticated) {
AuthorizationRequest authRequest;
var clientSessionVTR = VectorOfTrust.getDefaults();
if (Objects.nonNull(requestObject)) {
authRequest = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), CLIENT_ID).requestObject(requestObject).build();
} else {
clientSessionVTR = VectorOfTrust.parseFromAuthRequestAttribute(Collections.singletonList(vtrValue));
authRequest = new AuthenticationRequest.Builder(new ResponseType(ResponseType.Value.CODE), SCOPES, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(new Nonce()).customParameter("vtr", vtrValue).build();
}
var clientSession = new ClientSession(authRequest.toParameters(), LocalDateTime.now(), clientSessionVTR);
var clientRegistry = new ClientRegistry().setClientID(CLIENT_ID.getValue()).setClientName(CLIENT_NAME).setConsentRequired(consentRequired).setCookieConsentShared(cookieConsentShared).setClientType(clientType.getValue()).setIdentityVerificationSupported(identityVerificationSupport);
return UserContext.builder(SESSION.setAuthenticated(isAuthenticated)).withClientSession(clientSession).withClient(clientRegistry).build();
}
use of com.nimbusds.oauth2.sdk.AuthorizationRequest in project sandbox by backpaper0.
the class OAuth2Filter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse resp = (HttpServletResponse) response;
// OAuth 2.0のコールバック
if (req.getRequestURI().equals("/oauth2/callback")) {
try {
doCallback(req, resp);
} catch (IOException | ServletException e) {
throw e;
} catch (final Exception e) {
throw new ServletException(e);
}
return;
}
// セッションにユーザーがあるならログイン済み
final HttpSession session = req.getSession();
final Object user = session.getAttribute("user");
if (user != null) {
chain.doFilter(request, response);
return;
}
// 認可へ進む
final State state = new State();
final AuthorizationRequest authorizationRequest = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), clientID).scope(new Scope(scope)).state(state).redirectionURI(callbackURI).endpointURI(authzURI).build();
final URI requestURI = authorizationRequest.toURI();
session.setAttribute(state.getValue(), req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : ""));
resp.sendRedirect(requestURI.toString());
}
Aggregations