use of io.jans.as.model.jwk.JSONWebKeySet in project jans by JanssenProject.
the class JwtUtil method getJSONWebKeys.
public JSONWebKeySet getJSONWebKeys(String jwksUri) throws Exception {
log.debug("\n\n JwtUtil::getJSONWebKeys() - jwksUri = " + jwksUri + " \n");
JSONWebKeySet jsonWebKeySet = AuthClientFactory.getJSONWebKeys(jwksUri);
log.trace("\n\n JwtUtil::getJSONWebKeys() - jsonWebKeySet = " + jsonWebKeySet + " \n");
return jsonWebKeySet;
}
use of io.jans.as.model.jwk.JSONWebKeySet in project jans by JanssenProject.
the class JwtUtil method validateToken.
public void validateToken(String token, List<String> resourceScopes) throws InvalidJwtException, Exception {
log.trace("Validate Jwt Token - token = " + token + " ,resourceScopes = " + resourceScopes + "\n");
try {
// Parse Token
Jwt jwt = this.parse(token);
log.trace("JwtUtil::validateToken() -JWT details : " + " jwt.getSigningInput() = " + jwt.getSigningInput() + " ,jwt.getEncodedSignature() = " + jwt.getEncodedSignature() + " ,jwt.getHeader().getKeyId() = " + jwt.getHeader().getKeyId() + " ,jwt.getHeader().getSignatureAlgorithm() = " + jwt.getHeader().getSignatureAlgorithm() + " ,jwt.getClaims().getClaimAsString(JwtHeaderName.ALGORITHM) = " + jwt.getClaims().getClaimAsString(JwtHeaderName.ALGORITHM) + " ,jwt.getClaims().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD) = " + jwt.getClaims().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD) + ".");
final Date expiresAt = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
List<String> scopes = jwt.getClaims().getClaimAsStringList("scope");
log.debug("\n\n JwtUtil::validateToken() - expiresAt = " + expiresAt + " , issuer =" + issuer + " , scopes = " + scopes + "\n");
// Validate token is not expired
log.info("Validate JWT");
final Date now = new Date();
if (now.after(expiresAt)) {
log.error("ID Token is expired. (It is after " + now + ").");
throw new WebApplicationException("ID Token is expired", Response.status(Response.Status.UNAUTHORIZED).build());
}
// Validate issuer
log.info("Validate JWT Issuer");
if (!authUtil.isValidIssuer(issuer)) {
throw new WebApplicationException("Jwt Issuer is Invalid.", Response.status(Response.Status.UNAUTHORIZED).build());
}
// Retrieve JSON Web Key Set Uri
log.info("Retrieve JSON Web Key Set URI");
String jwksUri = this.getJwksUri(issuer);
log.trace("\n\n JwtUtil::validateToken() - jwksUri = " + jwksUri);
// Retrieve JSON Web Key Set
log.info("Retrieve JSON Web Key Set");
JSONWebKeySet jsonWebKeySet = this.getJSONWebKeys(jwksUri);
log.trace("\n\n JwtUtil::validateToken() - jsonWebKeySet = " + jsonWebKeySet);
// Verify the signature used to sign the access token
log.info("Verify JWT signature");
boolean isJwtSignatureValid = this.validateSignature(jwt, jsonWebKeySet);
log.debug("\n\n JwtUtil::validateToken() - isJwtSignatureValid = " + isJwtSignatureValid + "\n\n");
if (!isJwtSignatureValid) {
throw new WebApplicationException("Jwt Signature is Invalid.", Response.status(Response.Status.UNAUTHORIZED).build());
}
// Validate Scopes
log.info("Validate token scopes");
if (!authUtil.validateScope(scopes, resourceScopes)) {
log.error("Insufficient scopes. Required scope: " + resourceScopes + ", token scopes: " + scopes);
throw new WebApplicationException("Insufficient scopes. Required scope", Response.status(Response.Status.UNAUTHORIZED).build());
}
} catch (InvalidJwtException exp) {
log.error("Not a valid Jwt token = " + exp);
throw exp;
}
}
use of io.jans.as.model.jwk.JSONWebKeySet in project jans by JanssenProject.
the class JwtUtil method validateToken.
public List<String> validateToken(String token) throws InvalidJwtException, Exception {
try {
// Parse Token
Jwt jwt = this.parse(token);
log.trace("JwtUtil::validateToken() -JWT details : " + " jwt.getSigningInput() = " + jwt.getSigningInput() + " ,jwt.getEncodedSignature() = " + jwt.getEncodedSignature() + " ,jwt.getHeader().getKeyId() = " + jwt.getHeader().getKeyId() + " ,jwt.getHeader().getSignatureAlgorithm() = " + jwt.getHeader().getSignatureAlgorithm() + " ,jwt.getClaims().getClaimAsString(JwtHeaderName.ALGORITHM) = " + jwt.getClaims().getClaimAsString(JwtHeaderName.ALGORITHM) + " ,jwt.getClaims().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD) = " + jwt.getClaims().getClaimAsString(JwtHeaderName.ENCRYPTION_METHOD) + ".");
final Date expiresAt = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
String issuer = jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER);
List<String> scopes = jwt.getClaims().getClaimAsStringList("scope");
log.debug("\n\n JwtUtil::validateToken() - expiresAt = " + expiresAt + " , issuer =" + issuer + " , scopes = " + scopes + "\n");
// Validate token is not expired
log.info("Validate JWT");
final Date now = new Date();
if (now.after(expiresAt)) {
log.error("ID Token is expired. (It is after " + now + ").");
throw new WebApplicationException("ID Token is expired", Response.status(Response.Status.UNAUTHORIZED).build());
}
// Validate issuer
log.info("Validate JWT Issuer");
if (!authUtil.isValidIssuer(issuer)) {
throw new WebApplicationException("Jwt Issuer is Invalid.", Response.status(Response.Status.UNAUTHORIZED).build());
}
// Retrieve JSON Web Key Set Uri
log.info("Retrieve JSON Web Key Set URI");
String jwksUri = this.getJwksUri(issuer);
log.trace("\n\n JwtUtil::validateToken() - jwksUri = " + jwksUri);
// Retrieve JSON Web Key Set
log.info("Retrieve JSON Web Key Set");
JSONWebKeySet jsonWebKeySet = this.getJSONWebKeys(jwksUri);
log.trace("\n\n JwtUtil::validateToken() - jsonWebKeySet = " + jsonWebKeySet);
// Verify the signature used to sign the access token
log.info("Verify JWT signature");
boolean isJwtSignatureValid = this.validateSignature(jwt, jsonWebKeySet);
log.debug("\n\n JwtUtil::validateToken() - isJwtSignatureValid = " + isJwtSignatureValid + "\n\n");
if (!isJwtSignatureValid) {
throw new WebApplicationException("Jwt Signature is Invalid.", Response.status(Response.Status.UNAUTHORIZED).build());
}
return scopes;
} catch (InvalidJwtException exp) {
log.error("Not a valid Jwt token = " + exp);
throw exp;
}
}
use of io.jans.as.model.jwk.JSONWebKeySet in project jans by JanssenProject.
the class MTLSService method processMTLS.
public boolean processMTLS(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain, Client client) throws Exception {
log.debug("Trying to authenticate client {} via {} ...", client.getClientId(), client.getAuthenticationMethod());
final String clientCertAsPem = httpRequest.getHeader("X-ClientCert");
if (StringUtils.isBlank(clientCertAsPem)) {
log.debug("Client certificate is missed in `X-ClientCert` header, client_id: {}.", client.getClientId());
return false;
}
X509Certificate cert = CertUtils.x509CertificateFromPem(clientCertAsPem);
if (cert == null) {
log.debug("Failed to parse client certificate, client_id: {}.", client.getClientId());
return false;
}
final String cn = CertUtils.getCN(cert);
final String hashedCn = HashUtil.getHash(cn, SignatureAlgorithm.HS512);
if ((StringUtils.isBlank(cn) || StringUtils.isBlank(hashedCn)) || (!cn.equals(client.getClientId()) && !hashedCn.equals(HashUtil.getHash(client.getClientId(), SignatureAlgorithm.HS512)))) {
if (log.isTraceEnabled())
log.trace("Client certificate CN does not match clientId. Invoke registration script's isCertValidForClient, CN: {}, clientId: {}, hashedCn: {}", cn, client.getClientId(), hashedCn);
DynamicClientRegistrationContext context = new DynamicClientRegistrationContext(httpRequest, new JSONObject(), null, client);
boolean result = externalDynamicClientRegistrationService.isCertValidForClient(cert, context);
if (!result) {
log.error("Reject request. isCertValidForClient returned false.");
throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity(errorResponseFactory.getErrorAsJson(TokenErrorResponseType.INVALID_CLIENT, httpRequest.getParameter("state"), "")).build());
}
}
if (client.getAuthenticationMethod() == AuthenticationMethod.TLS_CLIENT_AUTH) {
log.debug("Authenticating with tls_client_auth ...");
final String subjectDn = client.getAttributes().getTlsClientAuthSubjectDn();
if (StringUtils.isBlank(subjectDn)) {
log.debug("SubjectDN is not set for client {} which is required to authenticate it via `tls_client_auth`.", client.getClientId());
return false;
}
// we check only `subjectDn`, the PKI certificate validation is performed by apache/httpd
if (CertUtils.equalsRdn(subjectDn, cert.getSubjectDN().getName())) {
log.debug("Client {} authenticated via `tls_client_auth`.", client.getClientId());
authenticatedSuccessfully(client, httpRequest);
filterChain.doFilter(httpRequest, httpResponse);
return true;
}
log.debug("Client's subject dn: {}, cert subject dn: {}", subjectDn, cert.getSubjectDN().getName());
}
if (client.getAuthenticationMethod() == AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH) {
// disable it
log.debug("Authenticating with self_signed_tls_client_auth ...");
final PublicKey publicKey = cert.getPublicKey();
final byte[] encodedKey = publicKey.getEncoded();
JSONObject jsonWebKeys = Strings.isNullOrEmpty(client.getJwks()) ? JwtUtil.getJSONWebKeys(client.getJwksUri()) : new JSONObject(client.getJwks());
if (jsonWebKeys == null) {
log.debug("Unable to load json web keys for client: {}, jwks_uri: {}, jks: {}", client.getClientId(), client.getJwksUri(), client.getJwks());
return false;
}
final JSONWebKeySet keySet = JSONWebKeySet.fromJSONObject(jsonWebKeys);
for (JSONWebKey key : keySet.getKeys()) {
if (ArrayUtils.isEquals(encodedKey, cryptoProvider.getPublicKey(key.getKid(), jsonWebKeys, null).getEncoded())) {
log.debug("Client {} authenticated via `self_signed_tls_client_auth`, matched kid: {}.", client.getClientId(), key.getKid());
authenticatedSuccessfully(client, httpRequest);
filterChain.doFilter(httpRequest, httpResponse);
return true;
}
}
}
log.debug("MTLS authentication failed.");
return false;
}
use of io.jans.as.model.jwk.JSONWebKeySet in project jans by JanssenProject.
the class AccountsServlet method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param servletRequest servlet request
* @param httpResponse servlet response
*/
protected void processRequest(HttpServletRequest servletRequest, HttpServletResponse httpResponse) {
log.info("Starting processRequest method of get Account Servlet***********************************************************************");
String authFromReq = null;
String xfapiinteractionid = null;
String tempaccess_token = null;
httpResponse.setCharacterEncoding("UTF-8");
httpResponse.setContentType(Constants.CONTENT_TYPE_APPLICATION_JSON_UTF_8);
try (PrintWriter out = httpResponse.getWriter()) {
xfapiinteractionid = servletRequest.getHeader("x-fapi-interaction-id");
tempaccess_token = servletRequest.getParameter("access_token");
if (xfapiinteractionid != null) {
httpResponse.addHeader("x-fapi-interaction-id", xfapiinteractionid);
} else {
xfapiinteractionid = UUID.randomUUID().toString();
httpResponse.addHeader("x-fapi-interaction-id", xfapiinteractionid);
}
if ((tempaccess_token != null) && (xfapiinteractionid != null)) {
if (tempaccess_token.startsWith("Bearer")) {
httpResponse.sendError(httpResponse.SC_BAD_REQUEST, "Bearer token in query is disallowed");
log.info("FAPI ACcount: Authorization Bearer Token is not allowed in query*********************************************");
// throw errorResponseFactory.createWebApplicationException(Response.Status.BAD_REQUEST, RegisterErrorResponseType.ACCESS_DENIED, "FAPI: access_token in query is disallowed.");
} else {
httpResponse.sendError(httpResponse.SC_BAD_REQUEST, "token in query is disallowed");
log.info("FAPI: Authorization token is non-Bearer is not allowed in query*********************************************");
}
}
String clientCertAsPem = servletRequest.getHeader("X-ClientCert");
if (clientCertAsPem != null) {
log.info("FAPI Account: clientCertAsPem found*****************************************" + clientCertAsPem);
} else
log.info("FAPI Account: Nooooooooo clientCertAsPem *****************************************");
authFromReq = servletRequest.getHeader("Authorization");
String clientDn = null;
Client cl = null;
clientDn = tokenService.getClientDn(authFromReq);
X509Certificate cert = CertUtils.x509CertificateFromPem(clientCertAsPem);
AuthorizationGrant authorizationGrant = tokenService.getBearerAuthorizationGrant(authFromReq);
if (authorizationGrant == null || cert == null) {
sendError(httpResponse, authorizationGrant == null ? "Unable to find authorization grant." : "Failed to parse client certificate.");
return;
}
PublicKey publicKey = cert.getPublicKey();
byte[] encodedKey = publicKey.getEncoded();
if (clientDn != null) {
log.info("FAPI Account: ClientDn from Authoirization(tokenService) *********************************************" + clientDn);
cl = clientService.getClientByDn(clientDn);
JSONObject jsonWebKeys = new JSONObject(cl.getJwks());
if (jsonWebKeys == null) {
log.debug("FAPI Account:********************Unable to load json web keys for client: {}, jwks_uri: {}, jks: {}", cl.getClientId(), cl.getJwksUri(), cl.getJwks());
}
int matchctr = 0;
final JSONWebKeySet keySet = JSONWebKeySet.fromJSONObject(jsonWebKeys);
try {
for (JSONWebKey key : keySet.getKeys()) {
if (ArrayUtils.isEquals(encodedKey, cryptoProvider.getPublicKey(key.getKid(), jsonWebKeys, null).getEncoded())) {
matchctr += 1;
log.debug("FAPI Account: ********************************Client {} authenticated via `self_signed_tls_client_auth`, matched kid: {}.", cl.getClientId(), key.getKid());
}
}
if (matchctr == 0) {
log.error("FAPI Account: Client certificate does not match clientId. clientId: " + cl.getClientId() + "*********************************************");
httpResponse.setStatus(401, "The resource owner or authorization server denied the request");
return;
// throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity(errorResponseFactory.getErrorAsJson(TokenErrorResponseType.INVALID_CLIENT, servletRequest.getParameter("state"), "")).build());
}
} catch (Exception e) {
log.info("FAPI Account: Exception while keymatching****************************************************************");
}
} else
log.info("FAPI Account: ClientDn from Authoirization(tokenService) is NULL*********************************************");
JSONObject jsonObj = new JSONObject();
JSONArray accounts = new JSONArray();
jsonObj.put("Links", new JSONObject().put("self", "/open-banking/v3.1/aisp/accounts"));
jsonObj.put("Meta", new JSONObject().put("TotalPages", 1));
accounts.put(getAccount("Account1", "GBP", "352413", "05 May 2021", "08 Jun 2021", "CurrentAccount", "Enabled", "Personal"));
accounts.put(getAccount("Account2", "GBP", "4736325", "25 Mar 2021", "23 Apr 2021", "CurrentAccount", "Enabled", "Personal"));
jsonObj.put("Data", new JSONObject().put("Account", accounts));
out.print(jsonObj.toString());
httpResponse.setStatus(200, "OK");
out.flush();
log.info("Finished processRequest method of get Account Servlet ***********************************************************************");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
Aggregations