use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.
the class OxAuthCryptoProvider method getSignatureAlgorithm.
public SignatureAlgorithm getSignatureAlgorithm(String alias) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
Certificate[] chain = keyStore.getCertificateChain(alias);
if ((chain == null) || chain.length == 0) {
return null;
}
X509Certificate cert = (X509Certificate) chain[0];
String sighAlgName = cert.getSigAlgName();
for (SignatureAlgorithm sa : SignatureAlgorithm.values()) {
if (sighAlgName.equalsIgnoreCase(sa.getAlgorithm())) {
return sa;
}
}
return null;
}
use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.
the class AbstractCryptoProvider method getPublicKey.
public PublicKey getPublicKey(String alias, JSONObject jwks) throws Exception {
java.security.PublicKey publicKey = null;
JSONArray webKeys = jwks.getJSONArray(JSON_WEB_KEY_SET);
for (int i = 0; i < webKeys.length(); i++) {
JSONObject key = webKeys.getJSONObject(i);
if (alias.equals(key.getString(KEY_ID))) {
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(key.getString(ALGORITHM));
if (signatureAlgorithm != null) {
if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.RSA)) {
publicKey = new RSAPublicKeyImpl(new BigInteger(1, Base64Util.base64urldecode(key.getString(MODULUS))), new BigInteger(1, Base64Util.base64urldecode(key.getString(EXPONENT))));
} else if (signatureAlgorithm.getFamily().equals(SignatureAlgorithmFamily.EC)) {
AlgorithmParameters parameters = AlgorithmParameters.getInstance(SignatureAlgorithmFamily.EC);
parameters.init(new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias()));
ECParameterSpec ecParameters = parameters.getParameterSpec(ECParameterSpec.class);
publicKey = KeyFactory.getInstance(SignatureAlgorithmFamily.EC).generatePublic(new ECPublicKeySpec(new ECPoint(new BigInteger(1, Base64Util.base64urldecode(key.getString(X))), new BigInteger(1, Base64Util.base64urldecode(key.getString(Y)))), ecParameters));
}
}
}
}
return publicKey;
}
use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.
the class UserInfoRestWebServiceImpl method requestUserInfo.
public Response requestUserInfo(String accessToken, String authorization, HttpServletRequest request, SecurityContext securityContext) {
if (authorization != null && !authorization.isEmpty() && authorization.startsWith("Bearer ")) {
accessToken = authorization.substring(7);
}
log.debug("Attempting to request User Info, Access token = {}, Is Secure = {}", accessToken, securityContext.isSecure());
Response.ResponseBuilder builder = Response.ok();
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(ServerUtil.getIpAddress(request), Action.USER_INFO);
try {
if (!UserInfoParamsValidator.validateParams(accessToken)) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_REQUEST));
} else {
AuthorizationGrant authorizationGrant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
if (authorizationGrant == null) {
builder = Response.status(400);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INVALID_TOKEN));
} else if (authorizationGrant.getAuthorizationGrantType() == AuthorizationGrantType.CLIENT_CREDENTIALS) {
builder = Response.status(403);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
} else if (!authorizationGrant.getScopes().contains(DefaultScope.OPEN_ID.toString()) && !authorizationGrant.getScopes().contains(DefaultScope.PROFILE.toString())) {
builder = Response.status(403);
builder.entity(errorResponseFactory.getErrorAsJson(UserInfoErrorResponseType.INSUFFICIENT_SCOPE));
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, false);
} else {
oAuth2AuditLog.updateOAuth2AuditLog(authorizationGrant, true);
CacheControl cacheControl = new CacheControl();
cacheControl.setPrivate(true);
cacheControl.setNoTransform(false);
cacheControl.setNoStore(true);
builder.cacheControl(cacheControl);
builder.header("Pragma", "no-cache");
User currentUser = authorizationGrant.getUser();
try {
currentUser = userService.getUserByDn(authorizationGrant.getUserDn());
} catch (EntryPersistenceException ex) {
log.warn("Failed to reload user entry: '{}'", authorizationGrant.getUserDn());
}
if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseAlg() != null && authorizationGrant.getClient().getUserInfoEncryptedResponseEnc() != null) {
KeyEncryptionAlgorithm keyEncryptionAlgorithm = KeyEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseAlg());
BlockEncryptionAlgorithm blockEncryptionAlgorithm = BlockEncryptionAlgorithm.fromName(authorizationGrant.getClient().getUserInfoEncryptedResponseEnc());
builder.type("application/jwt");
builder.entity(getJweResponse(keyEncryptionAlgorithm, blockEncryptionAlgorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
} else if (authorizationGrant.getClient() != null && authorizationGrant.getClient().getUserInfoSignedResponseAlg() != null) {
SignatureAlgorithm algorithm = SignatureAlgorithm.fromString(authorizationGrant.getClient().getUserInfoSignedResponseAlg());
builder.type("application/jwt");
builder.entity(getJwtResponse(algorithm, currentUser, authorizationGrant, authorizationGrant.getScopes()));
} else {
builder.type((MediaType.APPLICATION_JSON + ";charset=UTF-8"));
builder.entity(getJSonResponse(currentUser, authorizationGrant, authorizationGrant.getScopes()));
}
}
}
} 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 (SignatureException e) {
// 500
builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.error(e.getMessage(), e);
} catch (InvalidClaimException 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.crypto.signature.SignatureAlgorithm in project oxAuth by GluuFederation.
the class JwtSigner method newJwtSigner.
public static JwtSigner newJwtSigner(AppConfiguration appConfiguration, JSONWebKeySet webKeys, Client client) throws Exception {
Preconditions.checkNotNull(client);
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.fromString(appConfiguration.getDefaultSignatureAlgorithm());
if (client.getIdTokenSignedResponseAlg() != null) {
signatureAlgorithm = SignatureAlgorithm.fromString(client.getIdTokenSignedResponseAlg());
}
ClientService clientService = CdiUtil.bean(ClientService.class);
return new JwtSigner(appConfiguration, webKeys, signatureAlgorithm, client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
}
use of org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm 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;
}
Aggregations