Example usage for javax.naming AuthenticationException AuthenticationException

List of usage examples for javax.naming AuthenticationException AuthenticationException

Introduction

In this page you can find the example usage for javax.naming AuthenticationException AuthenticationException.

Prototype

public AuthenticationException(String explanation) 

Source Link

Document

Constructs a new instance of AuthenticationException using the explanation supplied.

Usage

From source file:org.zaproxy.zap.extension.zapwso2jiraplugin.JiraRestClient.java

public static void invokePutMethod(String auth, String url, String data)
        throws AuthenticationException, ClientHandlerException {
    Client client = Client.create();/*  ww w . j a v  a2  s  . c om*/
    WebResource webResource = client.resource(url);
    ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
            .accept("application/json").put(ClientResponse.class, data);
    int statusCode = response.getStatus();
    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new AuthenticationException("Invalid Username or Password");
    }
}

From source file:org.wso2.security.tools.scanner.dependency.js.ticketcreator.JIRARestClient.java

/**
 * Invoke Post method to add comment to created ticket.
 *
 * @param auth credentials info of JIRA.
 * @param url  url to be invoked./*from w  w  w  .j av  a2  s .co m*/
 * @param data data of API call.
 * @throws AuthenticationException Exception occurred while authenticate the JIRA.
 */
public void invokePostComment(String auth, String url, String data) throws AuthenticationException {
    Client client = Client.create();
    WebResource webResource = client.resource(url);
    WebResource.Builder builder = webResource.header("Authorization", "Basic " + auth);
    builder = builder.type("application/json");
    builder = builder.accept("application/json");
    ClientResponse response = builder.post(ClientResponse.class, data);
    int statusCode = response.getStatus();
    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new AuthenticationException("Invalid Username or Password");
    }
}

From source file:org.zaproxy.zap.extension.zapwso2jiraplugin.JiraRestClient.java

public static void invokeDeleteMethod(String auth, String url)
        throws AuthenticationException, ClientHandlerException {
    Client client = Client.create();/*ww w .  ja va  2 s .  c o  m*/
    WebResource webResource = client.resource(url);
    ClientResponse response = webResource.header("Authorization", "Basic " + auth).type("application/json")
            .accept("application/json").delete(ClientResponse.class);
    int statusCode = response.getStatus();
    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new AuthenticationException("Invalid Username or Password");
    }
}

From source file:edu.vt.middleware.ldap.auth.AbstractAuthenticator.java

/**
 * This will authenticate by binding to the LDAP with the supplied dn and
 * credential. Authentication will never succeed if {@link
 * AuthenticatorConfig#getAuthtype()} is set to 'none'. If retAttrs is null
 * and searchAttrs is true then all user attributes will be returned. If
 * retAttrs is an empty array and searchAttrs is true then no attributes will
 * be returned. This method throws AuthenticationException if authentication
 * fails and AuthorizationException if authorization fails.
 *
 * @param  dn  <code>String</code> for bind
 * @param  credential  <code>Object</code> for bind
 * @param  searchAttrs  <code>boolean</code> whether to perform attribute
 * search/*  www  .j a v a 2s  .  c  o  m*/
 * @param  retAttrs  <code>String[]</code> user attributes to return
 * @param  authResultHandler  <code>AuthenticationResultHandler[]</code> to
 * post process authentication results
 * @param  authzHandler  <code>AuthorizationHandler[]</code> to process
 * authorization after authentication
 *
 * @return  <code>Attribute</code> - belonging to the supplied user, returns
 * null if searchAttrs is false
 *
 * @throws  NamingException  if any of the ldap operations fail
 * @throws  AuthenticationException  if authentication fails
 * @throws  AuthorizationException  if authorization fails
 */
protected Attributes authenticateAndAuthorize(final String dn, final Object credential,
        final boolean searchAttrs, final String[] retAttrs,
        final AuthenticationResultHandler[] authResultHandler, final AuthorizationHandler[] authzHandler)
        throws NamingException {
    // check the authentication type
    final String authtype = this.config.getAuthtype();
    if (authtype.equalsIgnoreCase(LdapConstants.NONE_AUTHTYPE)) {
        throw new AuthenticationException("Cannot authenticate dn, authtype is 'none'");
    }

    // check the credential
    if (!LdapUtil.checkCredential(credential)) {
        throw new AuthenticationException("Cannot authenticate dn, invalid credential");
    }

    // check the dn
    if (dn == null || "".equals(dn)) {
        throw new AuthenticationException("Cannot authenticate dn, invalid dn");
    }

    Attributes userAttributes = null;

    // attempt to bind as this dn
    final ConnectionHandler ch = this.config.getConnectionHandler().newInstance();
    try {
        final AuthenticationCriteria ac = new AuthenticationCriteria(dn);
        ac.setCredential(credential);
        try {
            final AuthenticationHandler authHandler = this.config.getAuthenticationHandler().newInstance();
            authHandler.authenticate(ch, ac);
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Authentication succeeded for dn: " + dn);
            }
        } catch (AuthenticationException e) {
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Authentication failed for dn: " + dn);
            }
            if (authResultHandler != null && authResultHandler.length > 0) {
                for (AuthenticationResultHandler ah : authResultHandler) {
                    ah.process(ac, false);
                }
            }
            throw e;
        }
        // authentication succeeded, perform authorization if supplied
        if (authzHandler != null && authzHandler.length > 0) {
            for (AuthorizationHandler azh : authzHandler) {
                try {
                    azh.process(ac, ch.getLdapContext());
                    if (this.logger.isInfoEnabled()) {
                        this.logger.info("Authorization succeeded for dn: " + dn + " with handler: " + azh);
                    }
                } catch (AuthenticationException e) {
                    if (this.logger.isInfoEnabled()) {
                        this.logger.info("Authorization failed for dn: " + dn + " with handler: " + azh);
                    }
                    if (authResultHandler != null && authResultHandler.length > 0) {
                        for (AuthenticationResultHandler ah : authResultHandler) {
                            ah.process(ac, false);
                        }
                    }
                    throw e;
                }
            }
        }
        if (searchAttrs) {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Returning attributes: ");
                this.logger.debug("    " + (retAttrs == null ? "all attributes" : Arrays.toString(retAttrs)));
            }
            userAttributes = ch.getLdapContext().getAttributes(dn, retAttrs);
        }
        if (authResultHandler != null && authResultHandler.length > 0) {
            for (AuthenticationResultHandler ah : authResultHandler) {
                ah.process(ac, true);
            }
        }
    } finally {
        ch.close();
    }

    return userAttributes;
}

From source file:de.escidoc.sb.gsearch.xslt.EscidocCoreAccessor.java

/**
 * Calls resource for given rest-uri to get xml as String
 * (only works for content stored as xml). 
 * /*w  w w  . ja  v  a 2  s.c o m*/
 * @param restUri restUri
 * @param accessAsAnonymousUser 'true' or 'false' or empty (default is false) 
 * 
 * @return xml as String
 */
public static synchronized String getXml(final String restUri, final String accessAsAnonymousUser) {

    if (log.isDebugEnabled()) {
        log.debug("executing EscidocCoreAccessor, getXml");
    }
    if (restUri == null || restUri.isEmpty()) {
        return "";
    }
    BasicClientCookie cookie = null;
    try {
        if (accessAsAnonymousUser == null || !accessAsAnonymousUser.equals("true")) {
            cookie = new BasicClientCookie(COOKIE_LOGIN,
                    EscidocConfiguration.getInstance().get(EscidocConfiguration.GSEARCH_PASSWORD));
        }
        String domain = "";
        if (!restUri.startsWith("http")) {
            domain = EscidocConfiguration.getInstance().get(EscidocConfiguration.ESCIDOC_CORE_SELFURL);
        }
        String response = connectionUtility.getRequestURLAsString(new URL(domain + restUri), cookie);
        if (response.matches("(?s).*j_spring_security_check.*")) {
            throw new AuthenticationException("User with handle "
                    + EscidocConfiguration.getInstance().get(EscidocConfiguration.GSEARCH_PASSWORD)
                    + " not allowed to retrieve " + restUri);
        }
        return response;
    } catch (Exception e) {
        log.error("object with uri " + restUri + " not found: " + e.getMessage());
    }
    return "";
}

From source file:com.sonyericsson.jenkins.plugins.bfa.db.MongoDBKnowledgeBase.java

/**
 * Gets the DB./*from   w w w  . j a v  a  2  s .  com*/
 * @return The DB.
 * @throws UnknownHostException if the host cannot be found.
 * @throws AuthenticationException if we cannot authenticate towards the database.
 */
private DB getDb() throws UnknownHostException, AuthenticationException {
    if (db == null) {
        db = getMongoConnection().getDB(dbName);
    }
    if (Util.fixEmpty(userName) != null && Util.fixEmpty(Secret.toString(password)) != null) {
        char[] pwd = password.getPlainText().toCharArray();
        if (!db.authenticate(userName, pwd)) {
            throw new AuthenticationException("Could not athenticate with the mongo database");
        }
    }
    return db;
}

From source file:org.apache.pulsar.broker.authentication.AuthenticationProviderAthenz.java

@Override
public String authenticate(AuthenticationDataSource authData) throws AuthenticationException {
    SocketAddress clientAddress;//  w  w w .  j ava2  s  .c om
    String roleToken;

    if (authData.hasDataFromPeer()) {
        clientAddress = authData.getPeerAddress();
    } else {
        throw new AuthenticationException("Authentication data source does not have a client address");
    }

    if (authData.hasDataFromCommand()) {
        roleToken = authData.getCommandData();
    } else if (authData.hasDataFromHttp()) {
        roleToken = authData.getHttpHeader(AuthZpeClient.ZPE_TOKEN_HDR);
    } else {
        throw new AuthenticationException("Authentication data source does not have a role token");
    }

    if (roleToken == null) {
        throw new AuthenticationException("Athenz token is null, can't authenticate");
    }
    if (roleToken.isEmpty()) {
        throw new AuthenticationException("Athenz RoleToken is empty, Server is Using Athenz Authentication");
    }
    if (log.isDebugEnabled()) {
        log.debug("Athenz RoleToken : [{}] received from Client: {}", roleToken, clientAddress);
    }

    RoleToken token = new RoleToken(roleToken);

    if (!domainNameList.contains(token.getDomain())) {
        throw new AuthenticationException(
                String.format("Athenz RoleToken Domain mismatch, Expected: %s, Found: %s",
                        domainNameList.toString(), token.getDomain()));
    }

    // Synchronize for non-thread safe static calls inside athenz library
    synchronized (this) {
        PublicKey ztsPublicKey = AuthZpeClient.getZtsPublicKey(token.getKeyId());

        if (ztsPublicKey == null) {
            throw new AuthenticationException("Unable to retrieve ZTS Public Key");
        }

        if (token.validate(ztsPublicKey, allowedOffset, false, null)) {
            log.debug("Athenz Role Token : {}, Authenticated for Client: {}", roleToken, clientAddress);
            return token.getPrincipal();
        } else {
            throw new AuthenticationException(
                    String.format("Athenz Role Token Not Authenticated from Client: %s", clientAddress));
        }
    }
}

From source file:org.apache.pulsar.broker.authentication.AuthenticationProviderBasic.java

@Override
public String authenticate(AuthenticationDataSource authData) throws AuthenticationException {
    AuthParams authParams = new AuthParams(authData);
    String userId = authParams.getUserId();
    String password = authParams.getPassword();
    String msg = "Unknown user or invalid password";

    if (users.get(userId) == null) {
        throw new AuthenticationException(msg);
    }/* w  ww  .  j a  va 2 s .c  o m*/

    String encryptedPassword = users.get(userId);

    // For md5 algorithm
    if ((users.get(userId).startsWith("$apr1"))) {
        List<String> splitEncryptedPassword = Arrays.asList(encryptedPassword.split("\\$"));
        if (splitEncryptedPassword.size() != 4 || !encryptedPassword
                .equals(Md5Crypt.apr1Crypt(password.getBytes(), splitEncryptedPassword.get(2)))) {
            throw new AuthenticationException(msg);
        }
        // For crypt algorithm
    } else if (!encryptedPassword.equals(Crypt.crypt(password.getBytes(), encryptedPassword.substring(0, 2)))) {
        throw new AuthenticationException(msg);
    }

    return userId;
}

From source file:org.apache.pulsar.broker.authentication.AuthenticationProviderToken.java

private String getToken(AuthenticationDataSource authData) throws AuthenticationException {
    if (authData.hasDataFromCommand()) {
        // Authenticate Pulsar binary connection
        return authData.getCommandData();
    } else if (authData.hasDataFromHttp()) {
        // Authentication HTTP request. The format here should be compliant to RFC-6750
        // (https://tools.ietf.org/html/rfc6750#section-2.1). Eg: Authorization: Bearer xxxxxxxxxxxxx
        String httpHeaderValue = authData.getHttpHeader(HTTP_HEADER_NAME);
        if (httpHeaderValue == null || !httpHeaderValue.startsWith(HTTP_HEADER_VALUE_PREFIX)) {
            throw new AuthenticationException("Invalid HTTP Authorization header");
        }//from   w  ww  .  ja  v a  2 s.co m

        // Remove prefix
        String token = httpHeaderValue.substring(HTTP_HEADER_VALUE_PREFIX.length());
        return validateToken(token);
    } else {
        throw new AuthenticationException("No token credentials passed");
    }
}

From source file:org.apache.pulsar.broker.authentication.AuthenticationProviderToken.java

private String validateToken(final String token) throws AuthenticationException {
    if (StringUtils.isNotBlank(token)) {
        return token;
    } else {//from ww  w . j  a va 2  s  .c om
        throw new AuthenticationException("Blank token found");
    }
}