use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class RevokeRestWebServiceImpl method requestAccessToken.
@Override
public Response requestAccessToken(String token, String tokenTypeHint, String clientId, HttpServletRequest request, HttpServletResponse response, SecurityContext sec) {
log.debug("Attempting to revoke token: token = {}, tokenTypeHint = {}, isSecure = {}", token, tokenTypeHint, sec.isSecure());
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.TOKEN_REVOCATION);
validateToken(token);
Response.ResponseBuilder builder = Response.ok();
SessionClient sessionClient = identity.getSessionClient();
Client client = sessionClient != null ? sessionClient.getClient() : null;
if (client == null) {
client = clientService.getClient(clientId);
if (!clientService.isPublic(client)) {
log.trace("Client is not public and not authenticated. Skip revoking.");
return response(builder, oAuth2AuditLog);
}
}
if (client == null) {
log.trace("Client is not unknown. Skip revoking.");
return response(builder, oAuth2AuditLog);
}
oAuth2AuditLog.setClientId(client.getClientId());
TokenTypeHint tth = TokenTypeHint.getByValue(tokenTypeHint);
AuthorizationGrant authorizationGrant = null;
if (tth == TokenTypeHint.ACCESS_TOKEN) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(token);
} else if (tth == TokenTypeHint.REFRESH_TOKEN) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), token);
} else {
// Since the hint about the type of the token submitted for revocation is optional. oxAuth will
// search it as Access Token then as Refresh Token.
authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(token);
if (authorizationGrant == null) {
authorizationGrant = authorizationGrantList.getAuthorizationGrantByRefreshToken(client.getClientId(), token);
}
}
if (authorizationGrant == null) {
log.trace("Unable to find token.");
return response(builder, oAuth2AuditLog);
}
if (!authorizationGrant.getClientId().equals(client.getClientId())) {
log.trace("Token was issued with client {} but revoke is requested with client {}. Skip revoking.", authorizationGrant.getClientId(), client.getClientId());
return response(builder, oAuth2AuditLog);
}
RevokeTokenContext revokeTokenContext = new RevokeTokenContext(request, client, authorizationGrant, builder);
final boolean scriptResult = externalRevokeTokenService.revokeTokenMethods(revokeTokenContext);
if (!scriptResult) {
log.trace("Revoke is forbidden by 'Revoke Token' custom script (method returned false). Exit without revoking.");
return response(builder, oAuth2AuditLog);
}
grantService.removeAllByGrantId(authorizationGrant.getGrantId());
log.trace("Revoked successfully.");
return response(builder, oAuth2AuditLog);
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class DeviceAuthorizationRestWebServiceImpl method deviceAuthorization.
@Override
public Response deviceAuthorization(String clientId, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse, SecurityContext securityContext) {
// it may be encoded
scope = ServerUtil.urlDecode(scope);
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.DEVICE_CODE_AUTHORIZATION);
oAuth2AuditLog.setClientId(clientId);
oAuth2AuditLog.setScope(scope);
try {
log.debug("Attempting to request device codes: clientId = {}, scope = {}", clientId, scope);
SessionClient sessionClient = identity.getSessionClient();
Client client = sessionClient != null ? sessionClient.getClient() : null;
if (client == null) {
client = clientService.getClient(clientId);
if (!clientService.isPublic(client)) {
log.trace("Client is not public and not authenticated. Skip device authorization, clientId: {}", clientId);
throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, INVALID_CLIENT, "");
}
}
if (client == null) {
log.trace("Client is not unknown. Skip revoking.");
throw errorResponseFactory.createWebApplicationException(Response.Status.UNAUTHORIZED, INVALID_CLIENT, "");
}
if (!deviceAuthorizationService.hasDeviceCodeCompatibility(client)) {
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, INVALID_GRANT, "");
}
List<String> scopes = new ArrayList<>();
if (StringHelper.isNotEmpty(scope)) {
Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
scopes.addAll(grantedScopes);
}
// Entropy 20^8 which is suggested in the RFC8628 section 6.1
String userCode = StringUtils.generateRandomReadableCode((byte) 8);
// Entropy 160 bits which is over userCode entropy based on RFC8628 section 5.2
String deviceCode = StringUtils.generateRandomCode((byte) 24);
URI verificationUri = UriBuilder.fromUri(appConfiguration.getIssuer()).path("device-code").build();
int expiresIn = appConfiguration.getDeviceAuthzRequestExpiresIn();
int interval = appConfiguration.getDeviceAuthzTokenPollInterval();
long lastAccess = System.currentTimeMillis();
DeviceAuthorizationStatus status = DeviceAuthorizationStatus.PENDING;
DeviceAuthorizationCacheControl deviceAuthorizationCacheControl = new DeviceAuthorizationCacheControl(userCode, deviceCode, client, scopes, verificationUri, expiresIn, interval, lastAccess, status);
deviceAuthorizationService.saveInCache(deviceAuthorizationCacheControl, true, true);
log.info("Device authorization flow initiated, userCode: {}, deviceCode: {}, clientId: {}, verificationUri: {}, expiresIn: {}, interval: {}", userCode, deviceCode, clientId, verificationUri, expiresIn, interval);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return Response.ok().entity(getResponseJSONObject(deviceAuthorizationCacheControl).toString(4).replace("\\/", "/")).type(MediaType.APPLICATION_JSON_TYPE).build();
} catch (WebApplicationException wae) {
throw wae;
} catch (Exception e) {
log.error("Problems processing device authorization init flow, clientId: {}, scope: {}", clientId, scope, e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class RegisterRestWebServiceImpl method registerClientImpl.
private Response registerClientImpl(String requestParams, HttpServletRequest httpRequest, SecurityContext securityContext) {
Response.ResponseBuilder builder = Response.ok();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_REGISTRATION);
try {
final JSONObject requestObject = new JSONObject(requestParams);
final JSONObject softwareStatement = validateSoftwareStatement(httpRequest, requestObject);
if (softwareStatement != null) {
log.trace("Override request parameters by software_statement");
for (String key : softwareStatement.keySet()) {
requestObject.putOpt(key, softwareStatement.get(key));
}
}
final RegisterRequest r = RegisterRequest.fromJson(requestObject, appConfiguration.getLegacyDynamicRegistrationScopeParam());
if (requestObject.has(SOFTWARE_STATEMENT.toString())) {
r.setSoftwareStatement(requestObject.getString(SOFTWARE_STATEMENT.toString()));
}
log.info("Attempting to register client: applicationType = {}, clientName = {}, redirectUris = {}, isSecure = {}, sectorIdentifierUri = {}, defaultAcrValues = {}", r.getApplicationType(), r.getClientName(), r.getRedirectUris(), securityContext.isSecure(), r.getSectorIdentifierUri(), r.getDefaultAcrValues());
log.trace("Registration request = {}", requestParams);
if (!appConfiguration.getDynamicRegistrationEnabled()) {
log.info("Dynamic client registration is disabled.");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Dynamic client registration is disabled.");
}
if (!appConfiguration.getDynamicRegistrationPasswordGrantTypeEnabled() && registerParamsValidator.checkIfThereIsPasswordGrantType(r.getGrantTypes())) {
log.info("Password Grant Type is not allowed for Dynamic Client Registration.");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Password Grant Type is not allowed for Dynamic Client Registration.");
}
if (r.getSubjectType() == null) {
SubjectType defaultSubjectType = SubjectType.fromString(appConfiguration.getDefaultSubjectType());
if (defaultSubjectType != null) {
r.setSubjectType(defaultSubjectType);
} else if (appConfiguration.getSubjectTypesSupported().contains(SubjectType.PUBLIC.toString())) {
r.setSubjectType(SubjectType.PUBLIC);
} else if (appConfiguration.getSubjectTypesSupported().contains(SubjectType.PAIRWISE.toString())) {
r.setSubjectType(SubjectType.PAIRWISE);
}
}
// Throws a WebApplicationException whether a validation doesn't pass
registerParamsValidator.validateAlgorithms(r);
if (r.getIdTokenSignedResponseAlg() == null) {
r.setIdTokenSignedResponseAlg(SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm()));
}
if (r.getAccessTokenSigningAlg() == null) {
r.setAccessTokenSigningAlg(SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm()));
}
if (r.getClaimsRedirectUris() != null && !r.getClaimsRedirectUris().isEmpty()) {
if (!registerParamsValidator.validateRedirectUris(r.getGrantTypes(), r.getResponseTypes(), r.getApplicationType(), r.getSubjectType(), r.getClaimsRedirectUris(), r.getSectorIdentifierUri())) {
log.debug("Value of one or more claims_redirect_uris is invalid, claims_redirect_uris: " + r.getClaimsRedirectUris());
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLAIMS_REDIRECT_URI, "Value of one or more claims_redirect_uris is invalid");
}
}
if (!Strings.isNullOrEmpty(r.getInitiateLoginUri())) {
if (!registerParamsValidator.validateInitiateLoginUri(r.getInitiateLoginUri())) {
log.debug("The Initiate Login Uri is invalid. The initiate_login_uri must use the https schema: " + r.getInitiateLoginUri());
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLAIMS_REDIRECT_URI, "The Initiate Login Uri is invalid. The initiate_login_uri must use the https schema.");
}
}
final Pair<Boolean, String> validateResult = registerParamsValidator.validateParamsClientRegister(r.getApplicationType(), r.getSubjectType(), r.getGrantTypes(), r.getResponseTypes(), r.getRedirectUris());
if (!validateResult.getFirst()) {
log.trace("Client parameters are invalid, returns invalid_request error. Reason: " + validateResult.getSecond());
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, validateResult.getSecond());
}
if (!registerParamsValidator.validateRedirectUris(r.getGrantTypes(), r.getResponseTypes(), r.getApplicationType(), r.getSubjectType(), r.getRedirectUris(), r.getSectorIdentifierUri())) {
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_REDIRECT_URI, "Failed to validate redirect uris.");
}
if (!cibaRegisterParamsValidatorService.validateParams(r.getBackchannelTokenDeliveryMode(), r.getBackchannelClientNotificationEndpoint(), r.getBackchannelAuthenticationRequestSigningAlg(), r.getBackchannelUserCodeParameter(), r.getGrantTypes(), r.getSubjectType(), r.getSectorIdentifierUri(), r.getJwks(), r.getJwksUri())) {
// CIBA
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Invalid Client Metadata registering to use CIBA (Client Initiated Backchannel Authentication).");
}
registerParamsValidator.validateLogoutUri(r.getFrontChannelLogoutUris(), r.getRedirectUris(), errorResponseFactory);
registerParamsValidator.validateLogoutUri(r.getBackchannelLogoutUris(), r.getRedirectUris(), errorResponseFactory);
String clientsBaseDN = staticConfiguration.getBaseDn().getClients();
String inum = inumService.generateClientInum();
String generatedClientSecret = UUID.randomUUID().toString();
final Client client = new Client();
client.setDn("inum=" + inum + "," + clientsBaseDN);
client.setClientId(inum);
client.setDeletable(true);
client.setClientSecret(clientService.encryptSecret(generatedClientSecret));
client.setRegistrationAccessToken(HandleTokenFactory.generateHandleToken());
client.setIdTokenTokenBindingCnf(r.getIdTokenTokenBindingCnf());
final Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
client.setClientIdIssuedAt(calendar.getTime());
if (appConfiguration.getDynamicRegistrationExpirationTime() > 0) {
// #883 : expiration can be -1, mean does not expire
calendar.add(Calendar.SECOND, appConfiguration.getDynamicRegistrationExpirationTime());
client.setClientSecretExpiresAt(calendar.getTime());
client.setExpirationDate(calendar.getTime());
client.setTtl(appConfiguration.getDynamicRegistrationExpirationTime());
}
client.setDeletable(client.getClientSecretExpiresAt() != null);
if (StringUtils.isBlank(r.getClientName()) && r.getRedirectUris() != null && !r.getRedirectUris().isEmpty()) {
try {
URI redUri = new URI(r.getRedirectUris().get(0));
client.setClientName(redUri.getHost());
} catch (Exception e) {
// ignore
log.error(e.getMessage(), e);
client.setClientName("Unknown");
}
}
updateClientFromRequestObject(client, r, false);
boolean registerClient = true;
if (externalDynamicClientRegistrationService.isEnabled()) {
registerClient = externalDynamicClientRegistrationService.executeExternalCreateClientMethods(r, client);
}
if (!registerClient) {
log.trace("Client parameters are invalid, returns invalid_request error. External registration script returned false.");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.INVALID_CLIENT_METADATA, "External registration script returned false.");
}
Date currentTime = Calendar.getInstance().getTime();
client.setLastAccessTime(currentTime);
client.setLastLogonTime(currentTime);
Boolean persistClientAuthorizations = appConfiguration.getDynamicRegistrationPersistClientAuthorizations();
client.setPersistClientAuthorizations(persistClientAuthorizations != null ? persistClientAuthorizations : false);
clientService.persist(client);
JSONObject jsonObject = getJSONObject(client);
builder.entity(jsonObject.toString(4).replace("\\/", "/"));
log.info("Client registered: clientId = {}, applicationType = {}, clientName = {}, redirectUris = {}, sectorIdentifierUri = {}", client.getClientId(), client.getApplicationType(), client.getClientName(), client.getRedirectUris(), client.getSectorIdentifierUri());
oAuth2AuditLog.setClientId(client.getClientId());
oAuth2AuditLog.setScope(clientScopesToString(client));
oAuth2AuditLog.setSuccess(true);
} catch (StringEncrypter.EncryptionException e) {
builder = internalErrorResponse("Encryption exception occured.");
log.error(e.getMessage(), e);
} catch (JSONException e) {
builder = internalErrorResponse("Failed to parse JSON.");
log.error(e.getMessage(), e);
} catch (WebApplicationException e) {
log.error(e.getMessage(), e);
throw e;
} catch (Exception e) {
builder = internalErrorResponse("Unknown.");
log.error(e.getMessage(), e);
}
builder.cacheControl(ServerUtil.cacheControl(true, false));
builder.header("Pragma", "no-cache");
builder.type(MediaType.APPLICATION_JSON_TYPE);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class RegisterRestWebServiceImpl method requestClientUpdate.
@Override
public Response requestClientUpdate(String requestParams, String clientId, @HeaderParam("Authorization") String authorization, @Context HttpServletRequest httpRequest, @Context SecurityContext securityContext) {
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_UPDATE);
oAuth2AuditLog.setClientId(clientId);
try {
log.debug("Attempting to UPDATE client, client_id: {}, requestParams = {}, isSecure = {}", clientId, requestParams, securityContext.isSecure());
final String accessToken = tokenService.getToken(authorization);
if (StringUtils.isNotBlank(accessToken) && StringUtils.isNotBlank(clientId) && StringUtils.isNotBlank(requestParams)) {
JSONObject requestObject = new JSONObject(requestParams);
final JSONObject softwareStatement = validateSoftwareStatement(httpRequest, requestObject);
if (softwareStatement != null) {
log.trace("Override request parameters by software_statement");
for (String key : softwareStatement.keySet()) {
requestObject.putOpt(key, softwareStatement.get(key));
}
}
final RegisterRequest request = RegisterRequest.fromJson(requestObject, appConfiguration.getLegacyDynamicRegistrationScopeParam());
if (request != null) {
boolean redirectUrisValidated = true;
if (request.getRedirectUris() != null && !request.getRedirectUris().isEmpty()) {
redirectUrisValidated = registerParamsValidator.validateRedirectUris(request.getGrantTypes(), request.getResponseTypes(), request.getApplicationType(), request.getSubjectType(), request.getRedirectUris(), request.getSectorIdentifierUri());
}
if (redirectUrisValidated) {
if (!cibaRegisterParamsValidatorService.validateParams(request.getBackchannelTokenDeliveryMode(), request.getBackchannelClientNotificationEndpoint(), request.getBackchannelAuthenticationRequestSigningAlg(), request.getBackchannelUserCodeParameter(), request.getGrantTypes(), request.getSubjectType(), request.getSectorIdentifierUri(), request.getJwks(), request.getJwksUri())) {
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Invalid Client Metadata registering to use CIBA.")).build();
}
if (request.getSubjectType() != null && !appConfiguration.getSubjectTypesSupported().contains(request.getSubjectType().toString())) {
log.debug("Client UPDATE : parameter subject_type is invalid. Returns BAD_REQUEST response.");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "subject_type is invalid.")).build();
}
final Client client = clientService.getClient(clientId, accessToken);
if (client != null) {
updateClientFromRequestObject(client, request, true);
boolean updateClient = true;
if (externalDynamicClientRegistrationService.isEnabled()) {
updateClient = externalDynamicClientRegistrationService.executeExternalUpdateClientMethods(request, client);
}
if (updateClient) {
clientService.merge(client);
oAuth2AuditLog.setScope(clientScopesToString(client));
oAuth2AuditLog.setSuccess(true);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return Response.status(Response.Status.OK).entity(clientAsEntity(client)).build();
} else {
log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "External registration script returned false.")).build();
}
} else {
log.trace("The Access Token is not valid for the Client ID, returns invalid_token error.");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return Response.status(Response.Status.BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_TOKEN, "The Access Token is not valid for the Client ID.")).build();
}
}
}
}
log.debug("Client UPDATE : parameters are invalid. Returns BAD_REQUEST response.");
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return Response.status(Response.Status.BAD_REQUEST).entity(errorResponseFactory.errorAsJson(RegisterErrorResponseType.INVALID_CLIENT_METADATA, "Unknown.")).build();
} catch (WebApplicationException e) {
log.error(e.getMessage(), e);
throw e;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return internalErrorResponse("Unknown.").build();
}
use of org.gluu.oxauth.model.audit.OAuth2AuditLog in project oxAuth by GluuFederation.
the class SessionIdService method auditLogging.
private void auditLogging(SessionId sessionId) {
HttpServletRequest httpServletRequest = ServerUtil.getRequestOrNull();
if (httpServletRequest != null) {
Action action;
switch(sessionId.getState()) {
case AUTHENTICATED:
action = Action.SESSION_AUTHENTICATED;
break;
case UNAUTHENTICATED:
action = Action.SESSION_UNAUTHENTICATED;
break;
default:
action = Action.SESSION_UNAUTHENTICATED;
}
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpServletRequest), action);
oAuth2AuditLog.setSuccess(true);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
}
Aggregations