use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class ClientAssertion method load.
private boolean load(AppConfiguration appConfiguration, String clientId, ClientAssertionType clientAssertionType, String encodedAssertion) throws Exception {
boolean result;
if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
if (StringUtils.isNotBlank(encodedAssertion)) {
jwt = Jwt.parse(encodedAssertion);
// TODO: Store jti this value to check for duplicates
// Validate clientId
String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
String subject = jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER);
List<String> audience = jwt.getClaims().getClaimAsStringList(JwtClaimName.AUDIENCE);
Date expirationTime = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
//SignatureAlgorithm algorithm = SignatureAlgorithm.fromName(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
if ((clientId == null && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && issuer.equals(subject)) || (StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(issuer) && StringUtils.isNotBlank(subject) && clientId.equals(issuer) && issuer.equals(subject))) {
// Validate audience
String tokenUrl = appConfiguration.getTokenEndpoint();
if (audience != null && audience.contains(tokenUrl)) {
// Validate expiration
if (expirationTime.after(new Date())) {
ClientService clientService = CdiUtil.bean(ClientService.class);
Client client = clientService.getClient(subject);
// Validate client
if (client != null) {
JwtType jwtType = JwtType.fromString(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
AuthenticationMethod authenticationMethod = client.getAuthenticationMethod();
SignatureAlgorithm signatureAlgorithm = jwt.getHeader().getAlgorithm();
if (jwtType == null && signatureAlgorithm != null) {
jwtType = signatureAlgorithm.getJwtType();
}
if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && signatureAlgorithm.getFamily().equals("HMAC")) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (signatureAlgorithm.getFamily().equals("RSA") || signatureAlgorithm.getFamily().equals("EC"))))) {
clientSecret = clientService.decryptSecret(client.getClientSecret());
// Validate the crypto segment
String keyId = jwt.getHeader().getKeyId();
JSONObject jwks = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
String sharedSecret = clientService.decryptSecret(client.getClientSecret());
AbstractCryptoProvider cryptoProvider = CryptoProviderFactory.getCryptoProvider(appConfiguration);
boolean validSignature = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId, jwks, sharedSecret, signatureAlgorithm);
if (validSignature) {
result = true;
} else {
throw new InvalidJwtException("Invalid cryptographic segment");
}
} else {
throw new InvalidJwtException("Invalid authentication method");
}
} else {
throw new InvalidJwtException("Invalid client");
}
} else {
throw new InvalidJwtException("JWT has expired");
}
} else {
throw new InvalidJwtException("Invalid audience: " + audience + ", tokenUrl: " + tokenUrl);
}
} else {
throw new InvalidJwtException("Invalid clientId");
}
} else {
throw new InvalidJwtException("The Client Assertion is null or empty");
}
} else {
throw new InvalidJwtException("Invalid Client Assertion Type");
}
return result;
}
use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class AuthorizationGrant method createIdToken.
@Override
public IdToken createIdToken(String nonce, AuthorizationCode authorizationCode, AccessToken accessToken, AuthorizationGrant authorizationGrant, boolean includeIdTokenClaims) throws SignatureException, StringEncrypter.EncryptionException, InvalidJwtException, InvalidJweException {
try {
final IdToken idToken = createIdToken(this, nonce, authorizationCode, accessToken, getScopes(), includeIdTokenClaims);
final String acrValues = authorizationGrant.getAcrValues();
final String sessionDn = authorizationGrant.getSessionDn();
if (idToken.getExpiresIn() > 0) {
final TokenLdap tokenLdap = asToken(idToken);
tokenLdap.setAuthMode(acrValues);
tokenLdap.setSessionDn(sessionDn);
persist(tokenLdap);
}
// is it really neccessary to propagate to all tokens?
setAcrValues(acrValues);
setSessionDn(sessionDn);
// asynchronous save
save();
return idToken;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class AbstractJweDecrypter method decrypt.
@Override
public Jwe decrypt(String encryptedJwe) throws InvalidJweException {
try {
if (StringUtils.isBlank(encryptedJwe)) {
return null;
}
String[] jweParts = encryptedJwe.split("\\.");
if (jweParts.length != 5) {
throw new InvalidJwtException("Invalid JWS format.");
}
String encodedHeader = jweParts[0];
String encodedEncryptedKey = jweParts[1];
String encodedInitializationVector = jweParts[2];
String encodedCipherText = jweParts[3];
String encodedIntegrityValue = jweParts[4];
Jwe jwe = new Jwe();
jwe.setEncodedHeader(encodedHeader);
jwe.setEncodedEncryptedKey(encodedEncryptedKey);
jwe.setEncodedInitializationVector(encodedInitializationVector);
jwe.setEncodedCiphertext(encodedCipherText);
jwe.setEncodedIntegrityValue(encodedIntegrityValue);
jwe.setHeader(new JwtHeader(encodedHeader));
keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(jwe.getHeader().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD));
byte[] contentMasterKey = decryptEncryptionKey(encodedEncryptedKey);
byte[] initializationVector = Base64Util.base64urldecode(encodedInitializationVector);
byte[] authenticationTag = Base64Util.base64urldecode(encodedIntegrityValue);
byte[] additionalAuthenticatedData = jwe.getAdditionalAuthenticatedData().getBytes(Util.UTF8_STRING_ENCODING);
String plainText = decryptCipherText(encodedCipherText, contentMasterKey, initializationVector, authenticationTag, additionalAuthenticatedData);
jwe.setClaims(new JwtClaims(plainText));
return jwe;
} catch (InvalidJwtException e) {
throw new InvalidJweException(e);
} catch (UnsupportedEncodingException e) {
throw new InvalidJweException(e);
}
}
use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class AuthorizeRestWebServiceImpl method requestAuthorization.
public Response requestAuthorization(String scope, String responseType, String clientId, String redirectUri, String state, String respMode, String nonce, String display, String prompt, Integer maxAge, String uiLocalesStr, String idTokenHint, String loginHint, String acrValuesStr, String amrValuesStr, String request, String requestUri, String requestSessionState, String sessionState, String accessToken, String method, String originHeaders, String codeChallenge, String codeChallengeMethod, String customRespHeaders, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
// it may be encoded in uma case
scope = ServerUtil.urlDecode(scope);
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.USER_AUTHORIZATION);
oAuth2AuditLog.setClientId(clientId);
oAuth2AuditLog.setScope(scope);
// ATTENTION : please do not add more parameter in this debug method because it will not work with Seam 2.2.2.Final ,
// there is limit of 10 parameters (hardcoded), see: org.jboss.seam.core.Interpolator#interpolate
log.debug("Attempting to request authorization: " + "responseType = {}, clientId = {}, scope = {}, redirectUri = {}, nonce = {}, " + "state = {}, request = {}, isSecure = {}, requestSessionState = {}, sessionState = {}", responseType, clientId, scope, redirectUri, nonce, state, request, securityContext.isSecure(), requestSessionState, sessionState);
log.debug("Attempting to request authorization: " + "acrValues = {}, amrValues = {}, originHeaders = {}, codeChallenge = {}, codeChallengeMethod = {}", acrValuesStr, amrValuesStr, originHeaders, codeChallenge, codeChallengeMethod);
ResponseBuilder builder = Response.ok();
List<String> uiLocales = null;
if (StringUtils.isNotBlank(uiLocalesStr)) {
uiLocales = Util.splittedStringAsList(uiLocalesStr, " ");
}
List<ResponseType> responseTypes = ResponseType.fromString(responseType, " ");
List<Prompt> prompts = Prompt.fromString(prompt, " ");
List<String> acrValues = Util.splittedStringAsList(acrValuesStr, " ");
List<String> amrValues = Util.splittedStringAsList(amrValuesStr, " ");
ResponseMode responseMode = ResponseMode.getByValue(respMode);
SessionState sessionUser = identity.getSessionState();
User user = sessionUser != null && StringUtils.isNotBlank(sessionUser.getUserDn()) ? userService.getUserByDn(sessionUser.getUserDn()) : null;
try {
Map<String, String> customResponseHeaders = Util.jsonObjectArrayStringAsMap(customRespHeaders);
sessionStateService.assertAuthenticatedSessionCorrespondsToNewRequest(sessionUser, acrValuesStr);
if (!AuthorizeParamsValidator.validateParams(responseType, clientId, prompts, nonce, request, requestUri)) {
if (clientId != null && redirectUri != null && redirectionUriService.validateRedirectionUri(clientId, redirectUri) != null) {
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
} else {
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST, state));
}
} else {
Client client = clientService.getClient(clientId);
if (CollectionUtils.isEmpty(acrValues) && client != null && !ArrayUtils.isEmpty(client.getDefaultAcrValues())) {
acrValues = new ArrayList<String>();
acrValues.addAll(Arrays.asList(client.getDefaultAcrValues()));
}
JwtAuthorizationRequest jwtAuthorizationRequest = null;
if (client != null) {
List<String> scopes = new ArrayList<String>();
if (StringHelper.isNotEmpty(scope)) {
Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
scopes.addAll(grantedScopes);
}
// Validate redirectUri
redirectUri = redirectionUriService.validateRedirectionUri(clientId, redirectUri);
boolean validRedirectUri = redirectUri != null;
if (AuthorizeParamsValidator.validateResponseTypes(responseTypes, client)) {
if (validRedirectUri) {
if (StringUtils.isNotBlank(accessToken)) {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
if (authorizationGrant == null) {
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.ACCESS_DENIED, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
} else {
oAuth2AuditLog.setUsername(authorizationGrant.getUserId());
user = userService.getUser(authorizationGrant.getUserId());
sessionUser = sessionStateService.generateAuthenticatedSessionState(user.getDn(), prompt);
sessionUser.addPermission(client.getClientId(), true);
}
}
if (StringUtils.isNotBlank(requestUri)) {
boolean validRequestUri = false;
try {
URI reqUri = new URI(requestUri);
String reqUriHash = reqUri.getFragment();
String reqUriWithoutFragment = reqUri.getScheme() + ":" + reqUri.getSchemeSpecificPart();
ClientRequest clientRequest = new ClientRequest(reqUriWithoutFragment);
clientRequest.setHttpMethod(HttpMethod.GET);
ClientResponse<String> clientResponse = clientRequest.get(String.class);
int status = clientResponse.getStatus();
if (status == 200) {
request = clientResponse.getEntity(String.class);
if (StringUtils.isBlank(reqUriHash)) {
validRequestUri = true;
} else {
String hash = Base64Util.base64urlencode(JwtUtil.getMessageDigestSHA256(request));
validRequestUri = StringUtils.equals(reqUriHash, hash);
}
}
if (validRequestUri) {
requestUri = null;
} else {
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_REQUEST_URI, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
} catch (URISyntaxException e) {
log.error(e.getMessage(), e);
} catch (UnknownHostException e) {
log.error(e.getMessage(), e);
} catch (ConnectException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
boolean invalidOpenidRequestObject = false;
if (StringUtils.isNotBlank(request)) {
try {
jwtAuthorizationRequest = new JwtAuthorizationRequest(appConfiguration, request, client);
if (!jwtAuthorizationRequest.getResponseTypes().containsAll(responseTypes) || !responseTypes.containsAll(jwtAuthorizationRequest.getResponseTypes())) {
throw new InvalidJwtException("The responseType parameter is not the same in the JWT");
} else if (jwtAuthorizationRequest.getClientId() != null && !jwtAuthorizationRequest.getClientId().equals(clientId)) {
throw new InvalidJwtException("The clientId parameter is not the same in the JWT");
} else if (!jwtAuthorizationRequest.getScopes().containsAll(scopes) || !scopes.containsAll(jwtAuthorizationRequest.getScopes())) {
throw new InvalidJwtException("The scope parameter is not the same in the JWT");
} else if (jwtAuthorizationRequest.getRedirectUri() != null && !jwtAuthorizationRequest.getRedirectUri().equals(redirectUri)) {
throw new InvalidJwtException("The redirectUri parameter is not the same in the JWT");
} else if (jwtAuthorizationRequest.getState() != null && StringUtils.isNotBlank(state) && !jwtAuthorizationRequest.getState().equals(state)) {
throw new InvalidJwtException("The state parameter is not the same in the JWT");
} else if (jwtAuthorizationRequest.getNonce() != null && StringUtils.isNotBlank(nonce) && !jwtAuthorizationRequest.getNonce().equals(nonce)) {
throw new InvalidJwtException("The nonce parameter is not the same in the JWT");
} else if (jwtAuthorizationRequest.getDisplay() != null && StringUtils.isNotBlank(display) && !jwtAuthorizationRequest.getDisplay().getParamName().equals(display)) {
throw new InvalidJwtException("The display parameter is not the same in the JWT");
} else if (!jwtAuthorizationRequest.getPrompts().isEmpty() && !prompts.isEmpty() && !jwtAuthorizationRequest.getPrompts().containsAll(prompts)) {
throw new InvalidJwtException("The prompt parameter is not the same in the JWT");
} else if (jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null && maxAge != null && !jwtAuthorizationRequest.getIdTokenMember().getMaxAge().equals(maxAge)) {
throw new InvalidJwtException("The maxAge parameter is not the same in the JWT");
}
} catch (InvalidJwtException e) {
invalidOpenidRequestObject = true;
log.debug("Invalid JWT authorization request. Exception = {}, Message = {}", e, e.getClass().getName(), e.getMessage());
} catch (Exception e) {
invalidOpenidRequestObject = true;
log.debug("Invalid JWT authorization request. Exception = {}, Message = {}", e, e.getClass().getName(), e.getMessage());
}
}
if (invalidOpenidRequestObject) {
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.INVALID_OPENID_REQUEST_OBJECT, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
} else {
AuthorizationGrant authorizationGrant = null;
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
if (jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null) {
Claim userIdClaim = jwtAuthorizationRequest.getIdTokenMember().getClaim(JwtClaimName.SUBJECT_IDENTIFIER);
if (userIdClaim != null && userIdClaim.getClaimValue() != null && userIdClaim.getClaimValue().getValue() != null) {
String userIdClaimValue = userIdClaim.getClaimValue().getValue();
if (user != null) {
String userId = user.getUserId();
if (!userId.equalsIgnoreCase(userIdClaimValue)) {
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.USER_MISMATCHED, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
}
}
}
if (user == null) {
identity.logout();
if (prompts.contains(Prompt.NONE)) {
if (authenticationFilterService.isEnabled()) {
Map<String, String> params;
if (method.equals(HttpMethod.GET)) {
params = QueryStringDecoder.decode(httpRequest.getQueryString());
} else {
params = getGenericRequestMap(httpRequest);
}
String userDn = authenticationFilterService.processAuthenticationFilters(params);
if (userDn != null) {
Map<String, String> genericRequestMap = getGenericRequestMap(httpRequest);
Map<String, String> parameterMap = Maps.newHashMap(genericRequestMap);
Map<String, String> requestParameterMap = authenticationService.getAllowedParameters(parameterMap);
sessionUser = sessionStateService.generateAuthenticatedSessionState(userDn, prompt);
sessionUser.setSessionAttributes(requestParameterMap);
sessionStateService.createSessionStateCookie(sessionUser.getId(), httpResponse);
sessionStateService.updateSessionState(sessionUser);
user = userService.getUserByDn(sessionUser.getUserDn());
} else {
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.LOGIN_REQUIRED, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
} else {
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.LOGIN_REQUIRED, state));
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
} else {
if (prompts.contains(Prompt.LOGIN)) {
endSession(sessionState, httpRequest, httpResponse);
sessionState = null;
prompts.remove(Prompt.LOGIN);
}
redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
}
oAuth2AuditLog.setUsername(user.getUserId());
ClientAuthorizations clientAuthorizations = clientAuthorizationsService.findClientAuthorizations(user.getAttribute("inum"), client.getClientId());
if (clientAuthorizations != null && clientAuthorizations.getScopes() != null && Arrays.asList(clientAuthorizations.getScopes()).containsAll(scopes)) {
sessionUser.addPermission(clientId, true);
}
if (prompts.contains(Prompt.NONE) && client.getTrustedClient()) {
sessionUser.addPermission(clientId, true);
}
if (prompts.contains(Prompt.LOGIN)) {
endSession(sessionState, httpRequest, httpResponse);
sessionState = null;
prompts.remove(Prompt.LOGIN);
redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
if (prompts.contains(Prompt.CONSENT) || !sessionUser.isPermissionGrantedForClient(clientId)) {
prompts.remove(Prompt.CONSENT);
redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
// OXAUTH-37 : Validate authentication max age
boolean validAuthenticationMaxAge = true;
Integer authenticationMaxAge = null;
if (maxAge != null) {
authenticationMaxAge = maxAge;
} else if (!invalidOpenidRequestObject && jwtAuthorizationRequest != null && jwtAuthorizationRequest.getIdTokenMember() != null && jwtAuthorizationRequest.getIdTokenMember().getMaxAge() != null) {
authenticationMaxAge = jwtAuthorizationRequest.getIdTokenMember().getMaxAge();
}
GregorianCalendar now = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
GregorianCalendar userAuthenticationTime = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
userAuthenticationTime.setTime(sessionUser.getAuthenticationTime());
if (authenticationMaxAge != null) {
userAuthenticationTime.add(Calendar.SECOND, authenticationMaxAge);
validAuthenticationMaxAge = userAuthenticationTime.after(now);
} else if (client.getDefaultMaxAge() != null) {
userAuthenticationTime.add(Calendar.SECOND, client.getDefaultMaxAge());
validAuthenticationMaxAge = userAuthenticationTime.after(now);
}
if (!validAuthenticationMaxAge) {
endSession(sessionState, httpRequest, httpResponse);
sessionState = null;
redirectToAuthorizationPage(redirectUriResponse, responseTypes, scope, clientId, redirectUri, state, responseMode, nonce, display, prompts, maxAge, uiLocales, idTokenHint, loginHint, acrValues, amrValues, request, requestUri, originHeaders, codeChallenge, codeChallengeMethod, sessionState);
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
AuthorizationCode authorizationCode = null;
if (responseTypes.contains(ResponseType.CODE)) {
authorizationGrant = authorizationGrantList.createAuthorizationCodeGrant(user, client, sessionUser.getAuthenticationTime());
authorizationGrant.setNonce(nonce);
authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
authorizationGrant.setScopes(scopes);
authorizationGrant.setCodeChallenge(codeChallenge);
authorizationGrant.setCodeChallengeMethod(codeChallengeMethod);
// Store acr_values
authorizationGrant.setAcrValues(acrValuesStr);
authorizationGrant.setSessionDn(sessionUser.getDn());
// call save after object modification!!!
authorizationGrant.save();
authorizationCode = authorizationGrant.getAuthorizationCode();
redirectUriResponse.addResponseParameter("code", authorizationCode.getCode());
}
AccessToken newAccessToken = null;
if (responseTypes.contains(ResponseType.TOKEN)) {
if (authorizationGrant == null) {
authorizationGrant = authorizationGrantList.createImplicitGrant(user, client, sessionUser.getAuthenticationTime());
authorizationGrant.setNonce(nonce);
authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
authorizationGrant.setScopes(scopes);
// Store acr_values
authorizationGrant.setAcrValues(acrValuesStr);
authorizationGrant.setSessionDn(sessionUser.getDn());
// call save after object modification!!!
authorizationGrant.save();
}
newAccessToken = authorizationGrant.createAccessToken();
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.ACCESS_TOKEN, newAccessToken.getCode());
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.TOKEN_TYPE, newAccessToken.getTokenType().toString());
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.EXPIRES_IN, newAccessToken.getExpiresIn() + "");
}
if (responseTypes.contains(ResponseType.ID_TOKEN)) {
boolean includeIdTokenClaims = Boolean.TRUE.equals(appConfiguration.getLegacyIdTokenClaims());
if (authorizationGrant == null) {
includeIdTokenClaims = true;
authorizationGrant = authorizationGrantList.createAuthorizationGrant(user, client, sessionUser.getAuthenticationTime());
authorizationGrant.setNonce(nonce);
authorizationGrant.setJwtAuthorizationRequest(jwtAuthorizationRequest);
authorizationGrant.setScopes(scopes);
// Store authentication acr values
authorizationGrant.setAcrValues(acrValuesStr);
authorizationGrant.setSessionDn(sessionUser.getDn());
// call save after object modification, call is asynchronous!!!
authorizationGrant.save();
}
IdToken idToken = authorizationGrant.createIdToken(nonce, authorizationCode, newAccessToken, authorizationGrant, includeIdTokenClaims);
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.ID_TOKEN, idToken.getCode());
}
if (authorizationGrant != null && StringHelper.isNotEmpty(acrValuesStr)) {
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.ACR_VALUES, acrValuesStr);
}
//if (Boolean.valueOf(requestSessionState) && StringUtils.isBlank(sessionState) &&
if (sessionUser.getId() == null) {
final SessionState newSessionUser = sessionStateService.generateAuthenticatedSessionState(sessionUser.getUserDn(), prompt);
String newSessionState = newSessionUser.getId();
sessionUser.setId(newSessionState);
log.trace("newSessionState = {}", newSessionState);
}
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.SESSION_STATE, sessionUser.getId());
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.STATE, state);
if (scope != null && !scope.isEmpty()) {
scope = authorizationGrant.checkScopesPolicy(scope);
redirectUriResponse.addResponseParameter(AuthorizeResponseParam.SCOPE, scope);
}
clientService.updatAccessTime(client, false);
oAuth2AuditLog.setSuccess(true);
builder = RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest);
if (appConfiguration.getCustomHeadersWithAuthorizationResponse()) {
for (String key : customResponseHeaders.keySet()) {
builder.header(key, customResponseHeaders.get(key));
}
}
}
} else {
// Invalid redirectUri
builder = error(Response.Status.BAD_REQUEST, AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, // 400
state);
}
} else {
// Invalid responseTypes
// 400
builder = Response.status(Response.Status.BAD_REQUEST.getStatusCode());
builder.entity(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.UNSUPPORTED_RESPONSE_TYPE, state));
}
} else {
builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state);
}
}
// } catch (AcrChangedException e) {
// builder = Response.status(Response.Status.UNAUTHORIZED).entity("Session already exist with ACR that is different " +
// "than the one send with this authorization request. Please perform logout in order to login with another ACR. ACR: " + acrValuesStr);
// log.error(e.getMessage(), e);
} catch (AcrChangedException e) {
// Acr changed
log.error("ACR is changed, please use prompt=login in order to alter existing session.");
log.error(e.getMessage(), e);
RedirectUri redirectUriResponse = new RedirectUri(redirectUri, responseTypes, responseMode);
redirectUriResponse.parseQueryString(errorResponseFactory.getErrorAsQueryString(AuthorizeErrorResponseType.SESSION_SELECTION_REQUIRED, state));
redirectUriResponse.addResponseParameter("hint", "Use prompt=login in order to alter existing session.");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return RedirectUtil.getRedirectResponseBuilder(redirectUriResponse, httpRequest).build();
} catch (EntryPersistenceException e) {
// Invalid clientId
builder = error(Response.Status.UNAUTHORIZED, AuthorizeErrorResponseType.UNAUTHORIZED_CLIENT, state);
log.error(e.getMessage(), e);
} catch (SignatureException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (StringEncrypter.EncryptionException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (InvalidJwtException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (Exception e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
use of org.xdi.oxauth.model.exception.InvalidJwtException in project oxAuth by GluuFederation.
the class AuthenticationFilter method processJwtAuth.
private void processJwtAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) {
boolean authorized = false;
try {
if (servletRequest.getParameter("client_assertion") != null && servletRequest.getParameter("client_assertion_type") != null) {
String clientId = servletRequest.getParameter("client_id");
ClientAssertionType clientAssertionType = ClientAssertionType.fromString(servletRequest.getParameter("client_assertion_type"));
String encodedAssertion = servletRequest.getParameter("client_assertion");
if (clientAssertionType == ClientAssertionType.JWT_BEARER) {
ClientAssertion clientAssertion = new ClientAssertion(appConfiguration, clientId, clientAssertionType, encodedAssertion);
String username = clientAssertion.getSubjectIdentifier();
String password = clientAssertion.getClientSecret();
// Identity.username and user isn't authenticated
if (!username.equals(identity.getCredentials().getUsername()) || !identity.isLoggedIn()) {
identity.getCredentials().setUsername(username);
identity.getCredentials().setPassword(password);
authenticator.authenticateWebService(true);
authorized = true;
}
}
}
filterChain.doFilter(servletRequest, servletResponse);
} catch (ServletException ex) {
log.info("JWT authentication failed: {}", ex);
} catch (IOException ex) {
log.info("JWT authentication failed: {}", ex);
} catch (InvalidJwtException ex) {
log.info("JWT authentication failed: {}", ex);
}
try {
if (!authorized) {
sendError(servletResponse);
}
} catch (IOException ex) {
}
}
Aggregations