use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.
the class UmaTokenService method requestRpt.
public Response requestRpt(String grantType, String ticket, String claimToken, String claimTokenFormat, String pctCode, String rptCode, String scope, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
try {
log.trace("requestRpt grant_type: {}, ticket: {}, claim_token: {}, claim_token_format: {}, pct: {}, rpt: {}, scope: {}", grantType, ticket, claimToken, claimTokenFormat, pctCode, rptCode, scope);
umaValidationService.validateGrantType(grantType);
List<UmaPermission> permissions = umaValidationService.validateTicket(ticket);
Jwt idToken = umaValidationService.validateClaimToken(claimToken, claimTokenFormat);
UmaPCT pct = umaValidationService.validatePct(pctCode);
UmaRPT rpt = umaValidationService.validateRPT(rptCode);
Client client = umaValidationService.validate(identity.getSessionClient().getClient());
Map<Scope, Boolean> scopes = umaValidationService.validateScopes(scope, permissions, client);
// creates new pct if pct is null in request
pct = pctService.updateClaims(pct, idToken, client.getClientId(), permissions);
Claims claims = new Claims(idToken, pct, claimToken);
Map<UmaScriptByScope, UmaAuthorizationContext> scriptMap = umaNeedsInfoService.checkNeedsInfo(claims, scopes, permissions, pct, httpRequest, client);
if (!scriptMap.isEmpty()) {
expressionService.evaluate(scriptMap, permissions);
} else {
if (log.isWarnEnabled())
log.warn("There are no any policies that protects scopes. Scopes: {}. Configuration property umaGrantAccessIfNoPolicies: {}", UmaScopeService.asString(scopes.keySet()), appConfiguration.getUmaGrantAccessIfNoPolicies());
if (appConfiguration.getUmaGrantAccessIfNoPolicies() != null && appConfiguration.getUmaGrantAccessIfNoPolicies()) {
log.warn("Access granted because there are no any protection. Make sure it is intentional behavior.");
} else {
log.warn("Access denied because there are no any protection. Make sure it is intentional behavior.");
throw errorResponseFactory.createWebApplicationException(Response.Status.FORBIDDEN, UmaErrorResponseType.FORBIDDEN_BY_POLICY, "Access denied because there are no any protection. Make sure it is intentional behavior.");
}
}
log.trace("Access granted.");
updatePermissionsWithClientRequestedScope(permissions, scopes);
addPctToPermissions(permissions, pct);
boolean upgraded = false;
if (rpt == null) {
ExecutionContext executionContext = new ExecutionContext(httpRequest, httpResponse);
executionContext.setClient(client);
rpt = rptService.createRPTAndPersist(executionContext, permissions);
rptCode = rpt.getNotHashedCode();
} else if (rptService.addPermissionToRPT(rpt, permissions)) {
upgraded = true;
}
UmaTokenResponse response = new UmaTokenResponse();
response.setAccessToken(rptCode);
response.setUpgraded(upgraded);
response.setTokenType("Bearer");
response.setPct(pct.getCode());
return Response.ok(ServerUtil.asJson(response)).build();
} catch (Exception ex) {
log.error("Exception happened", ex);
if (ex instanceof WebApplicationException) {
throw (WebApplicationException) ex;
}
}
log.error("Failed to handle request to UMA Token Endpoint.");
throw errorResponseFactory.createWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, UmaErrorResponseType.SERVER_ERROR, "Failed to handle request to UMA Token Endpoint.");
}
use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.
the class AudienceTest method setAudience_withAdditionalClaims_shouldResultInAdditionalClaimsPresentinAud.
@Test
public void setAudience_withAdditionalClaims_shouldResultInAdditionalClaimsPresentinAud() {
JwtClaims claims = new JwtClaims();
Client client = new Client();
client.setClientId("clientId");
client.getAttributes().setAdditionalAudience(Lists.newArrayList("aud1", "aud2"));
Audience.setAudience(claims, client);
assertEquals(claims.getClaim("aud"), Lists.newArrayList("clientId", "aud1", "aud2"));
}
use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.
the class ClientAssertion method load.
private boolean load(AppConfiguration appConfiguration, AbstractCryptoProvider cryptoProvider, String clientId, io.jans.as.model.token.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();
String parUrl = StringUtils.isNotBlank(appConfiguration.getParEndpoint()) ? appConfiguration.getParEndpoint() : "";
String cibaAuthUrl = appConfiguration.getBackchannelAuthenticationEndpoint();
if (audience != null && (audience.contains(appConfiguration.getIssuer()) || audience.contains(tokenUrl) || audience.contains(parUrl) || audience.contains(cibaAuthUrl))) {
// 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().getSignatureAlgorithm();
if (jwtType == null && signatureAlgorithm != null) {
jwtType = signatureAlgorithm.getJwtType();
}
if (jwtType != null && signatureAlgorithm != null && signatureAlgorithm.getFamily() != null && ((authenticationMethod == AuthenticationMethod.CLIENT_SECRET_JWT && AlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) || (authenticationMethod == AuthenticationMethod.PRIVATE_KEY_JWT && (AlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily()) || AlgorithmFamily.EC.equals(signatureAlgorithm.getFamily()))))) {
if (client.getTokenEndpointAuthSigningAlg() == null || SignatureAlgorithm.fromString(client.getTokenEndpointAuthSigningAlg()).equals(signatureAlgorithm)) {
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());
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 signing algorithm");
}
} 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);
}
} 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 io.jans.as.common.model.registration.Client in project jans by JanssenProject.
the class CorsFilter method doFilterImpl.
protected Collection<String> doFilterImpl(ServletRequest servletRequest) throws IOException, ServletException {
Collection<String> globalAllowedOrigins = getAllowedOrigins();
if (StringHelper.isNotEmpty(servletRequest.getParameter("client_id"))) {
String clientId = servletRequest.getParameter("client_id");
Client client = clientService.getClient(clientId);
if (client != null) {
String[] authorizedOriginsArray = client.getAuthorizedOrigins();
if (authorizedOriginsArray != null && authorizedOriginsArray.length > 0) {
List<String> clientAuthorizedOrigins = Arrays.asList(authorizedOriginsArray);
setAllowedOrigins(clientAuthorizedOrigins);
}
}
} else {
final HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
String header = httpRequest.getHeader("Authorization");
if (httpRequest.getRequestURI().endsWith("/token")) {
if (header != null && header.startsWith("Basic ")) {
String base64Token = header.substring(6);
String token = new String(Base64.decodeBase64(base64Token), StandardCharsets.UTF_8);
String username = "";
int delim = token.indexOf(":");
if (delim != -1) {
username = URLDecoder.decode(token.substring(0, delim), Util.UTF8_STRING_ENCODING);
}
Client client = clientService.getClient(username);
if (client != null) {
String[] authorizedOriginsArray = client.getAuthorizedOrigins();
if (authorizedOriginsArray != null && authorizedOriginsArray.length > 0) {
List<String> clientAuthorizedOrigins = Arrays.asList(authorizedOriginsArray);
setAllowedOrigins(clientAuthorizedOrigins);
}
}
}
}
}
return globalAllowedOrigins;
}
use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.
the class RegisterRestWebServiceImpl method registerClientImpl.
private Response registerClientImpl(String requestParams, HttpServletRequest httpRequest, SecurityContext securityContext) {
errorResponseFactory.validateComponentEnabled(ComponentType.REGISTRATION);
Response.ResponseBuilder builder = Response.status(Response.Status.CREATED);
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(httpRequest), Action.CLIENT_REGISTRATION);
try {
final JSONObject requestObject = parseRequestObjectWithoutValidation(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));
}
}
if (isTrue(appConfiguration.getDcrSignatureValidationEnabled())) {
validateRequestObject(requestParams, softwareStatement, httpRequest);
}
final RegisterRequest r = RegisterRequest.fromJson(requestObject);
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 (isFalse(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 (isTrue(appConfiguration.getDcrAuthorizationWithClientCredentials()) && !r.getGrantTypes().contains(GrantType.CLIENT_CREDENTIALS)) {
log.info("Register request does not contain grant_type=client_credentials, however dcrAuthorizationWithClientCredentials=true which is forbidden.");
throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "Client Credentials Grant Type is not present in Dynamic Client Registration request.");
}
if (r.getSubjectType() == null) {
SubjectType defaultSubjectType = SubjectType.fromString(appConfiguration.getDefaultSubjectType());
if (defaultSubjectType != null) {
r.setSubjectType(defaultSubjectType);
} else if (appConfiguration.getSubjectTypesSupported().contains(io.jans.as.model.common.SubjectType.PUBLIC.toString())) {
r.setSubjectType(io.jans.as.model.common.SubjectType.PUBLIC);
} else if (appConfiguration.getSubjectTypesSupported().contains(io.jans.as.model.common.SubjectType.PAIRWISE.toString())) {
r.setSubjectType(io.jans.as.model.common.SubjectType.PAIRWISE);
}
}
// Throws a WebApplicationException whether a validation doesn't pass
registerParamsValidator.validateAlgorithms(r);
// Default Signature Algorithm
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() && !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()) && !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_CLIENT_METADATA, "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 (isFalse(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.");
}
validateSubjectIdentifierAttribute(r);
if (!cibaRegisterParamsValidatorService.validateParams(r.getBackchannelTokenDeliveryMode(), r.getBackchannelClientNotificationEndpoint(), r.getBackchannelAuthenticationRequestSigningAlg(), 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.getFrontChannelLogoutUri(), 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);
setClientName(r, client);
updateClientFromRequestObject(client, r, false);
boolean registerClient = true;
if (externalDynamicClientRegistrationService.isEnabled()) {
registerClient = externalDynamicClientRegistrationService.executeExternalCreateClientMethods(r, client, httpRequest);
}
if (!registerClient) {
// clear cache to force reload from persistence
clientService.removeFromCache(client);
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);
client.setPersistClientAuthorizations(isTrue(appConfiguration.getDynamicRegistrationPersistClientAuthorizations()));
clientService.persist(client);
JSONObject jsonObject = getJSONObject(client);
jsonObject = modifyPostScript(jsonObject, new ExecutionContext(httpRequest, null).setClient(client));
builder.entity(jsonObjectToString(jsonObject));
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) {
if (log.isErrorEnabled())
log.error(e.getMessage(), e);
throw e;
} catch (Exception e) {
builder = internalErrorResponse(Constants.UNKNOWN_DOT);
log.error(e.getMessage(), e);
}
builder.cacheControl(ServerUtil.cacheControl(true, false));
builder.header(Constants.PRAGMA, Constants.NO_CACHE);
builder.type(MediaType.APPLICATION_JSON_TYPE);
applicationAuditLogger.sendMessage(oAuth2AuditLog);
return builder.build();
}
Aggregations