Example usage for javax.security.sasl AuthenticationException AuthenticationException

List of usage examples for javax.security.sasl AuthenticationException AuthenticationException

Introduction

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

Prototype

public AuthenticationException(String detail) 

Source Link

Document

Constructs a new instance of AuthenticationException with a detailed message.

Usage

From source file:StringUtilities.java

/**
 * A directive is a parameter of the digest authentication process.
 * Returns the value of a directive from the map. If mandatory is true and the 
 * value is null, then it throws an {@link AuthenticationException}.
 *  /*from ww w .  jav  a  2  s . c o m*/
 * @param directivesMap the directive's map 
 * @param directive the name of the directive we want to retrieve
 * @param mandatory is the directive mandatory
 * @return the mandatory value as a String
 * @throws AuthenticationException if mandatory is true and if 
 * directivesMap.get(directive) == null
 */
public static String getDirectiveValue(HashMap<String, String> directivesMap, String directive,
        boolean mandatory) throws AuthenticationException {
    String value = directivesMap.get(directive);
    if (value == null) {
        if (mandatory) {
            throw new AuthenticationException("\"" + directive + "\" mandatory directive is missing");
        }

        return "";
    }

    return value;
}

From source file:org.apache.hive.service.auth.LdapAuthenticationProviderImpl.java

private DirSearch createDirSearch(String user, String password) throws AuthenticationException {
    if (StringUtils.isBlank(user)) {
        throw new AuthenticationException(
                "Error validating LDAP user:" + " a null or blank user name has been provided");
    }// w  w  w.  jav  a 2 s .  c o m
    if (StringUtils.isBlank(password) || password.getBytes()[0] == 0) {
        throw new AuthenticationException(
                "Error validating LDAP user:" + " a null or blank password has been provided");
    }
    List<String> principals = LdapUtils.createCandidatePrincipals(conf, user);
    for (Iterator<String> iterator = principals.iterator(); iterator.hasNext();) {
        String principal = iterator.next();
        try {
            return searchFactory.getInstance(conf, principal, password);
        } catch (AuthenticationException ex) {
            if (!iterator.hasNext()) {
                throw ex;
            }
        }
    }
    throw new AuthenticationException(String.format("No candidate principals for %s was found.", user));
}

From source file:com.telefonica.iot.cosmos.hive.authprovider.OAuth2AuthenticationProviderImpl.java

@Override
public void Authenticate(String user, String token) throws AuthenticationException {
    // create the Http client
    HttpClient httpClient = httpClientFactory.getHttpClient(true);

    // create the request
    String url = idmEndpoint + "/user?access_token=" + token;
    HttpRequestBase request = new HttpGet(url);

    // do the request
    HttpResponse httpRes = null;/*  w  w w . ja  va  2 s .c om*/

    try {
        httpRes = httpClient.execute(request);
        LOGGER.debug("Doing request: " + request.toString());
    } catch (IOException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // get the input streamResponse
    String streamResponse = "";

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpRes.getEntity().getContent()));
        streamResponse = reader.readLine();
        LOGGER.debug("Response received: " + streamResponse);
    } catch (IOException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // parse the input streamResponse as a Json
    JSONObject jsonResponse = null;

    try {
        JSONParser jsonParser = new JSONParser();
        jsonResponse = (JSONObject) jsonParser.parse(streamResponse);
    } catch (ParseException e) {
        throw new AuthenticationException(e.getMessage());
    } // try catch

    // check if the given token does not exist
    if (jsonResponse.containsKey("error")) {
        throw new AuthenticationException("The given token does not exist");
    } // if

    // check if the obtained user id matches the given user
    if (jsonResponse.containsKey("id") && !jsonResponse.get("id").equals(user)) {
        throw new AuthenticationException("The given token does not match the given user");
    } // if

    // release the connection
    request.releaseConnection();

    LOGGER.debug("User " + user + " authenticated");
}

From source file:org.jevis.rest.Config.java

public static JEVisDataSource getJEVisDS(HttpHeaders httpHeaders) throws AuthenticationException {
    if (httpHeaders.getRequestHeader("authorization") == null
            || httpHeaders.getRequestHeader("authorization").isEmpty()) {
        throw new AuthenticationException("Authorization header is missing");
    }/*from   w  w w  .  j  a va2 s  . co  m*/
    String auth = httpHeaders.getRequestHeader("authorization").get(0);
    if (auth != null && !auth.isEmpty()) {
        auth = auth.replaceFirst("[Bb]asic ", "");

        System.out.println("Auth: '" + auth + "'");
        byte[] decoded2 = DatatypeConverter.parseBase64Binary(auth);
        //            if (Base64.isBase64(auth.getBytes())) {
        byte[] decoded = Base64.decodeBase64(auth);
        String debugFuck = ("1: " + Arrays.toString(decoded2) + "\n" + "2: " + Arrays.toString(decoded) + "\n"
                + "Equal: " + Arrays.equals(decoded, decoded2));

        try {
            //InitialContext()
            String decodeS = (new String(decoded, "UTF-8"));
            String decodeS2 = (new String(decoded));

            //                String decodeS = (new String(decoded, "UTF-8") + "\n");
            String[] dauth = decodeS.split(":");
            if (dauth.length == 2) {

                String username = dauth[0];
                String password = dauth[1];
                //                    String username = "Sys Admin";
                //                    String password = "OpenJEVis2016";

                System.out.println("Username: '" + username + "'   PW: '" + password + "'");
                try {
                    JEVisDataSource ds = Config.getDS(username, password);

                    try {
                        if (ds.connect(username, password)) {
                            return ds;
                        } else {
                            //                                throw new AuthenticationException("Username/Password is not correct.1");
                            throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2001,
                                    "Username/Password is not correct.");
                        }
                    } catch (JEVisException jex) {
                        throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2002,
                                "Username/Password is not correct.");
                    }

                } catch (JEVisException ex) {
                    //                        throw new AuthenticationException("Could not connect to Database:\n" + ex);
                    throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2001,
                            "Username/Password is not correct.");
                }
            } else {
                //                    throw new AuthenticationException("The HTML authorization header is not correct formate");
                throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2002,
                        "The HTML authorization header is not correct formate");
            }
        } catch (UnsupportedEncodingException uee) {
            //                throw new AuthenticationException("The HTML authorization header is not in Base64");
            throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2003,
                    "The HTML authorization header is not in Base64");
        }
        //            } else {
        //                throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2003, "The HTML authorization header is not in Base64");
        //            }
    } else {
        //            throw new AuthenticationException("The HTML authorization header is missing or emty");
        throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2004,
                "The HTML authorization header is missing or emty");
    }

}

From source file:uk.ac.diamond.shibbolethecpauthclient.ShibbolethECPAuthClient.java

/**
 * Attempts to authenticate the user and password against the IdP and SP this client
 * was initialized with. /*from  w ww .ja v  a  2 s .c  o m*/
 * 
 * @param username The username on the IdP to authenticate
 * @param password The password to authenticate the username with
 * @return A SAML Response from the Identity Provider
 * 
 * @throws IOException
 * thrown if the client encounters a problem
 * @throws AuthenticationException
 * thrown if the client could not authenticate the username + password
 * @throws SOAPClientException
 * thrown if either Service Provider or Identity Provider are not configured for ECP
 */
@SuppressWarnings("deprecation")
public org.opensaml.saml2.core.Response authenticate(String username, String password)
        throws IOException, AuthenticationException, SOAPClientException {

    // -- Connecting to SP, defer processing to parent class ------------------------------
    HttpResponse res = super.execute(new HttpGet(SP));
    log.info("Status: " + res.getStatusLine());
    for (Header h : res.getAllHeaders()) {
        log.debug(h.getName() + ": " + h.getValue());
    }
    String entity = EntityUtils.toString(res.getEntity()); // Warning: This closes the getEntity() InputStream!!
    log.debug("HttpResponse::Content: " + entity);

    if (!isSamlSoapResponse(res)) {
        throw new SOAPClientException("Service Provider not configured to accept ECP messages");
    }

    // -- Parse PAOS response -------------------------------------------------------------
    Envelope initialLoginSoapResponse = getSoapMessage(new StringEntity(entity)); // turn the string back into an entity

    // -- Pass the SOAP request from the SP to the IdP ------------------------------------
    Envelope idpLoginSoapRequest = new EnvelopeBuilder().buildObject();
    Body b = initialLoginSoapResponse.getBody();
    b.detach();
    idpLoginSoapRequest.setBody(b);

    // -- Try logging in to the IdP using HTTP BASIC authentication -----------------------
    log.debug("Logging into IdP [" + IdP + "]");
    HttpPost idpLoginRequest = new HttpPost(IdP);
    // Use the parent's AUTH_IN_PROGRESS string because it manages the pre-processing of a HTTP request
    idpLoginRequest.getParams().setBooleanParameter(super.getAuthInProgress(), true);
    idpLoginRequest.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.encodeBytes((username + ":" + password).getBytes()));
    idpLoginRequest.setEntity(new StringEntity(xmlToString(idpLoginSoapRequest)));
    HttpResponse idpLoginResponse = super.execute(idpLoginRequest);

    // -- Handle HTTP log-in response from the IdP ----------------------------------------
    log.debug("Status: " + idpLoginResponse.getStatusLine());
    if (idpLoginResponse.getStatusLine().getStatusCode() != 200) {
        throw new AuthenticationException(idpLoginResponse.getStatusLine().toString());
    }

    String idpEntity = EntityUtils.toString(idpLoginResponse.getEntity()); // Warning: This closes the getEntity() InputStream!!
    log.debug("HttpResponse::Content: " + idpEntity);

    // -- Parse SAML SOAP response from the IdP -------------------------------------------
    Envelope idpLoginSoapResponse = getSoapMessage(new StringEntity(idpEntity)); // turn the string back into an entity

    // Get the consumer service URL (should be the SP's SOAP/ECP access point - we should check)
    String assertionConsumerServiceURL = ((org.opensaml.saml2.ecp.Response) idpLoginSoapResponse.getHeader()
            .getUnknownXMLObjects(org.opensaml.saml2.ecp.Response.DEFAULT_ELEMENT_NAME).get(0))
                    .getAssertionConsumerServiceURL();
    log.debug("assertionConsumerServiceURL: " + assertionConsumerServiceURL);

    // SAML will only use the first response in a SOAP message
    List<XMLObject> responses = idpLoginSoapResponse.getBody()
            .getUnknownXMLObjects(Response.DEFAULT_ELEMENT_NAME);
    if (!responses.isEmpty()) {
        Response response = (Response) responses.get(0);

        // Get root code (?)
        StatusCode sc = response.getStatus().getStatusCode();
        while (sc.getStatusCode() != null) {
            sc = sc.getStatusCode();
        }

        // Hm, they don't like us
        if (StatusCode.AUTHN_FAILED_URI.equals(sc.getValue())) {
            throw new AuthenticationException(sc.getValue());
        }

        // return the SAML response we got
        return response;
    }

    return null;
}