Search in sources :

Example 36 with Client

use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.

the class AuthenticationFilter method processMTLS.

/**
 * @return whether successful or not
 */
private boolean processMTLS(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain) throws Exception {
    if (cryptoProvider == null) {
        log.debug("Unable to create cryptoProvider.");
        return false;
    }
    final String clientId = httpRequest.getParameter(Constants.CLIENT_ID);
    if (StringUtils.isNotBlank(clientId)) {
        final Client client = clientService.getClient(clientId);
        if (client != null && (client.getAuthenticationMethod() == io.jans.as.model.common.AuthenticationMethod.TLS_CLIENT_AUTH || client.getAuthenticationMethod() == io.jans.as.model.common.AuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH)) {
            return mtlsService.processMTLS(httpRequest, httpResponse, filterChain, client);
        }
    } else {
        final String requestUrl = httpRequest.getRequestURL().toString();
        boolean isRegisterEndpoint = requestUrl.endsWith("/register");
        boolean isRegistration = "POST".equalsIgnoreCase(httpRequest.getMethod());
        if (appConfiguration.getDcrAuthorizationWithMTLS() && isRegistration && isRegisterEndpoint) {
            return mtlsService.processRegisterMTLS(httpRequest);
        }
    }
    return false;
}
Also used : Client(io.jans.as.common.model.registration.Client)

Example 37 with Client

use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.

the class AuthenticationFilter method processAuthByAccessToken.

private void processAuthByAccessToken(String accessToken, HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain filterChain) {
    try {
        log.trace("Authenticating client by access token {} ...", accessToken);
        if (StringUtils.isBlank(accessToken)) {
            sendError(httpResponse);
            return;
        }
        AuthorizationGrant grant = authorizationGrantList.getAuthorizationGrantByAccessToken(accessToken);
        if (grant == null) {
            sendError(httpResponse);
            return;
        }
        final AbstractToken accessTokenObj = grant.getAccessToken(accessToken);
        if (accessTokenObj == null || !accessTokenObj.isValid()) {
            sendError(httpResponse);
            return;
        }
        Client client = grant.getClient();
        authenticator.configureSessionClient(client);
        filterChain.doFilter(httpRequest, httpResponse);
        return;
    } catch (Exception ex) {
        log.error("Failed to authenticate client by access_token", ex);
    }
    sendError(httpResponse);
}
Also used : AbstractToken(io.jans.as.server.model.common.AbstractToken) Client(io.jans.as.common.model.registration.Client) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) ServletException(javax.servlet.ServletException) InvalidJwtException(io.jans.as.model.exception.InvalidJwtException) WebApplicationException(javax.ws.rs.WebApplicationException) IOException(java.io.IOException)

Example 38 with Client

use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.

the class Authenticator method clientAuthentication.

public boolean clientAuthentication(Credentials credentials, boolean interactive, boolean skipPassword) {
    boolean isServiceUsesExternalAuthenticator = !interactive && externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.SERVICE);
    if (isServiceUsesExternalAuthenticator) {
        CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.SERVICE, 1, this.authAcr);
        if (customScriptConfiguration == null) {
            logger.error("Failed to get CustomScriptConfiguration. acr: '{}'", this.authAcr);
        } else {
            this.authAcr = customScriptConfiguration.getCustomScript().getName();
            boolean result = externalAuthenticationService.executeExternalAuthenticate(customScriptConfiguration, null, 1);
            logger.info("Authentication result for user '{}', result: '{}'", credentials.getUsername(), result);
            if (result) {
                Client client = authenticationService.configureSessionClient();
                showClientAuthenticationLog(client);
                return true;
            }
        }
    }
    boolean loggedIn = skipPassword;
    if (!loggedIn) {
        loggedIn = clientService.authenticate(credentials.getUsername(), credentials.getPassword());
    }
    if (loggedIn) {
        Client client = authenticationService.configureSessionClient();
        showClientAuthenticationLog(client);
        return true;
    }
    return false;
}
Also used : Client(io.jans.as.common.model.registration.Client) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 39 with Client

use of io.jans.as.common.model.registration.Client in project jans by JanssenProject.

the class ExternalResourceOwnerPasswordCredentialsService method executeExternalAuthenticate.

public boolean executeExternalAuthenticate(ExternalResourceOwnerPasswordCredentialsContext context) {
    final Client client = context.getExecutionContext().getClient();
    final List<CustomScriptConfiguration> scripts = getCustomScriptConfigurationsByDns(client.getAttributes().getRopcScripts());
    if (scripts == null || scripts.isEmpty()) {
        log.debug("There is no any external ROPC scripts assigned to client {}.", client.getClientId());
        return false;
    }
    for (CustomScriptConfiguration script : scripts) {
        if (!executeExternalAuthenticate(script, context)) {
            log.debug("Stopped running external ROPC scripts because script {} returns false.", script.getName());
            return false;
        }
    }
    return true;
}
Also used : Client(io.jans.as.common.model.registration.Client) CustomScriptConfiguration(io.jans.model.custom.script.conf.CustomScriptConfiguration)

Example 40 with Client

use of io.jans.as.common.model.registration.Client 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);
    }
}
Also used : JSONWebKeySet(io.jans.as.model.jwk.JSONWebKeySet) PublicKey(java.security.PublicKey) JSONArray(org.json.JSONArray) X509Certificate(java.security.cert.X509Certificate) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) JSONWebKey(io.jans.as.model.jwk.JSONWebKey) JSONObject(org.json.JSONObject) Client(io.jans.as.common.model.registration.Client) AuthorizationGrant(io.jans.as.server.model.common.AuthorizationGrant) PrintWriter(java.io.PrintWriter)

Aggregations

Client (io.jans.as.common.model.registration.Client)70 WebApplicationException (javax.ws.rs.WebApplicationException)20 InvalidJwtException (io.jans.as.model.exception.InvalidJwtException)12 JSONObject (org.json.JSONObject)12 Test (org.testng.annotations.Test)12 User (io.jans.as.common.model.common.User)11 BaseComponentTest (io.jans.as.server.BaseComponentTest)10 Calendar (java.util.Calendar)10 GregorianCalendar (java.util.GregorianCalendar)10 IOException (java.io.IOException)9 OAuth2AuditLog (io.jans.as.server.model.audit.OAuth2AuditLog)8 AuthorizationGrant (io.jans.as.server.model.common.AuthorizationGrant)8 ExecutionContext (io.jans.as.server.model.common.ExecutionContext)8 JSONException (org.json.JSONException)8 Jwt (io.jans.as.model.jwt.Jwt)7 Response (javax.ws.rs.core.Response)7 SessionClient (io.jans.as.server.model.session.SessionClient)6 ProtectedApi (io.jans.configapi.core.rest.ProtectedApi)6 ServletException (javax.servlet.ServletException)6 SignatureAlgorithm (io.jans.as.model.crypto.signature.SignatureAlgorithm)5