Example usage for javax.security.auth.login LoginException LoginException

List of usage examples for javax.security.auth.login LoginException LoginException

Introduction

In this page you can find the example usage for javax.security.auth.login LoginException LoginException.

Prototype

public LoginException(String msg) 

Source Link

Document

Constructs a LoginException with the specified detail message.

Usage

From source file:org.jboss.datavirt.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * Gets the current HTTP servlet request.
 * @throws PolicyContextException//from   w ww.  jav a 2 s .  c om
 */
private HttpServletRequest getCurrentRequest() throws LoginException {
    HttpServletRequest request = HttpRequestThreadLocalValve.TL_request.get();
    if (request == null) {
        try {
            request = (HttpServletRequest) PolicyContext.getContext("javax.servlet.http.HttpServletRequest");
        } catch (Exception e) {
            request = null;
        }
    }
    if (request == null) {
        throw new LoginException("Failed to get current HTTP request.");
    }
    return request;
}

From source file:org.nuxeo.ecm.platform.login.NuxeoLoginModule.java

@SuppressWarnings({ "unchecked" })
protected NuxeoPrincipal getPrincipal() throws LoginException {
    UserIdentificationInfo userIdent = null;

    // **** init the callbacks
    // Std login/password callbacks
    NameCallback nc = new NameCallback("Username: ", SecurityConstants.ANONYMOUS);
    PasswordCallback pc = new PasswordCallback("Password: ", false);

    // Nuxeo specific cb : handle LoginPlugin initialization
    UserIdentificationInfoCallback uic = new UserIdentificationInfoCallback();

    // JBoss specific cb : handle web=>ejb propagation
    // SecurityAssociationCallback ac = new SecurityAssociationCallback();
    // ObjectCallback oc = new ObjectCallback("UserInfo:");

    // **** handle callbacks
    // We can't check the callback handler class to know what will be
    // supported/*w ww.  ja va2 s .  c om*/
    // because the cbh is wrapped by JAAS
    // => just try and swalow exceptions
    // => will be externalised to plugins via EP to avoid JBoss dependency
    boolean cb_handled = false;

    try {
        // only try this cbh when called from the web layer
        if (useUserIdentificationInfoCB) {
            callbackHandler.handle(new Callback[] { uic });
            // First check UserInfo CB return
            userIdent = uic.getUserInfo();
            cb_handled = true;
        }
    } catch (UnsupportedCallbackException e) {
        log.debug("UserIdentificationInfoCallback is not supported");
    } catch (IOException e) {
        log.warn("Error calling callback handler with UserIdentificationInfoCallback : " + e.getMessage());
    }

    Principal principal = null;
    Object credential = null;

    if (!cb_handled) {
        CallbackResult result = loginPluginManager.handleSpecifcCallbacks(callbackHandler);

        if (result != null && result.cb_handled) {
            if (result.userIdent != null && result.userIdent.containsValidIdentity()) {
                userIdent = result.userIdent;
                cb_handled = true;
            } else {
                principal = result.principal;
                credential = result.credential;
                if (principal != null) {
                    cb_handled = true;
                }
            }
        }
    }

    if (!cb_handled) {
        try {
            // Std CBH : will only works for L/P
            callbackHandler.handle(new Callback[] { nc, pc });
            cb_handled = true;
        } catch (UnsupportedCallbackException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        } catch (IOException e) {
            LoginException le = new LoginException("Authentications Failure - " + e.getMessage());
            le.initCause(e);
        }
    }

    // Login via the Web Interface : may be using a plugin
    if (userIdent != null && userIdent.containsValidIdentity()) {
        NuxeoPrincipal nxp = validateUserIdentity(userIdent);

        if (nxp != null) {
            sharedState.put("javax.security.auth.login.name", nxp.getName());
            sharedState.put("javax.security.auth.login.password", userIdent);
        }
        return nxp;
    }

    if (LoginComponent.isSystemLogin(principal)) {
        return new SystemPrincipal(principal.getName());
    }
    // if (principal instanceof NuxeoPrincipal) { // a nuxeo principal
    // return validatePrincipal((NuxeoPrincipal) principal);
    // } else
    if (principal != null) { // a non null principal
        String password = null;
        if (credential instanceof char[]) {
            password = new String((char[]) credential);
        } else if (credential != null) {
            password = credential.toString();
        }
        return validateUsernamePassword(principal.getName(), password);
    } else { // we don't have a principal - try the username &
        // password
        String username = nc.getName();
        if (username == null) {
            return null;
        }
        char[] password = pc.getPassword();
        return validateUsernamePassword(username, password != null ? new String(password) : null);
    }
}

From source file:org.overlord.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * Gets the current HTTP servlet request.
 * @throws PolicyContextException/* w ww . j  a va2  s  . c om*/
 */
private HttpServletRequest getCurrentRequest() throws LoginException {
    HttpServletRequest request = HttpRequestThreadLocalValve.TL_request.get();
    if (request == null) {
        try {
            request = (HttpServletRequest) PolicyContext.getContext("javax.servlet.http.HttpServletRequest"); //$NON-NLS-1$
        } catch (Exception e) {
            request = null;
        }
    }
    if (request == null) {
        throw new LoginException("Failed to get current HTTP request."); //$NON-NLS-1$
    }
    return request;
}

From source file:org.nuxeo.duoweb.authentication.DuoFactorsAuthenticator.java

public Principal createIdentity(String username) throws LoginException {
    UserManager manager = Framework.getService(UserManager.class);
    Random random = new Random(System.currentTimeMillis());
    log.debug("createIdentity: " + username);
    try {//from   w  ww.ja  va  2 s .  c  om
        NuxeoPrincipal principal;
        if (manager == null) {
            principal = new NuxeoPrincipalImpl(username);
        } else {
            principal = manager.getPrincipal(username);
            if (principal == null) {
                throw new LoginException(String.format("principal %s does not exist", username));
            }
        }
        String principalId = String.valueOf(random.nextLong());
        principal.setPrincipalId(principalId);
        return principal;
    } catch (LoginException | ClientException e) {
        log.error("createIdentity failed", e);
        LoginException le = new LoginException("createIdentity failed for" + " user " + username);
        le.initCause(e);
        throw le;
    }
}

From source file:net.dv8tion.jda.core.entities.impl.JDAImpl.java

public void verifyToken() throws LoginException, RateLimitedException {
    RestAction<JSONObject> login = new RestAction<JSONObject>(this, Route.Self.GET_SELF.compile()) {
        @Override/* w  w  w.j  a  v  a  2  s  .c o  m*/
        protected void handleResponse(Response response, Request<JSONObject> request) {
            if (response.isOk())
                request.onSuccess(response.getObject());
            else if (response.isRateLimit())
                request.onFailure(new RateLimitedException(request.getRoute(), response.retryAfter));
            else if (response.code == 401)
                request.onSuccess(null);
            else
                request.onFailure(new LoginException(
                        "When verifying the authenticity of the provided token, Discord returned an unknown response:\n"
                                + response.toString()));
        }
    };

    JSONObject userResponse;
    try {
        userResponse = login.complete(false);
    } catch (RuntimeException e) {
        //We check if the LoginException is masked inside of a ExecutionException which is masked inside of the RuntimeException
        Throwable ex = e.getCause() != null ? e.getCause().getCause() : null;
        if (ex instanceof LoginException)
            throw (LoginException) ex;
        else
            throw e;
    }

    if (userResponse != null) {
        verifyToken(userResponse);
    } else {
        //If we received a null return for userResponse, then that means we hit a 401.
        // 401 occurs we attempt to access the users/@me endpoint with the wrong token prefix.
        // e.g: If we use a Client token and prefix it with "Bot ", or use a bot token and don't prefix it.
        // It also occurs when we attempt to access the endpoint with an invalid token.
        //The code below already knows that something is wrong with the token. We want to determine if it is invalid
        // or if the developer attempted to login with a token using the wrong AccountType.

        //If we attempted to login as a Bot, remove the "Bot " prefix and set the Requester to be a client.
        if (getAccountType() == AccountType.BOT) {
            token = token.replace("Bot ", "");
            requester = new Requester(this, AccountType.CLIENT);
        } else //If we attempted to login as a Client, prepend the "Bot " prefix and set the Requester to be a Bot
        {
            token = "Bot " + token;
            requester = new Requester(this, AccountType.BOT);
        }

        try {
            //Now that we have reversed the AccountTypes, attempt to get User info again.
            userResponse = login.complete(false);
        } catch (RuntimeException e) {
            //We check if the LoginException is masked inside of a ExecutionException which is masked inside of the RuntimeException
            Throwable ex = e.getCause() != null ? e.getCause().getCause() : null;
            if (ex instanceof LoginException)
                throw (LoginException) ex;
            else
                throw e;
        }

        //If the response isn't null (thus it didn't 401) send it to the secondary verify method to determine
        // which account type the developer wrongly attempted to login as
        if (userResponse != null)
            verifyToken(userResponse);
        else //We 401'd again. This is an invalid token
            throw new LoginException("The provided token is invalid!");
    }
}

From source file:net.dv8tion.jda.entities.impl.JDAImpl.java

public void verifyToken(String token) throws LoginException {
    this.authToken = token;
    Requester.Response response = getRequester().get(Requester.DISCORD_API_PREFIX + "users/@me");

    if (response.isOk()) {
        JSONObject json = response.getObject();
        if (!json.has("bot") || !json.getBoolean("bot"))
            throw new RuntimeException("Attempted to login as a BOT with a CLIENT token!");
    } else if (response.isRateLimit())
        throw new RateLimitedException(response.getObject().getInt("retry_after"));
    else {//from  w w  w.j av a 2 s .  co m
        if (response.code == 401) {
            throw new LoginException("The provided token was invalid!");
        } else {
            throw new LoginException(
                    "When verifying the authenticity of the provided token, Discord returned an unknown response:\n"
                            + response.toString());
        }
    }
}

From source file:org.esbtools.auth.jboss.CertLdapLoginModule.java

@Override
protected Group[] getRoleSets() throws LoginException {
    LOGGER.debug("staticRoleLoginModule getRoleSets()");

    String roleName = (String) options.get(AUTH_ROLE_NAME);

    SimpleGroup userRoles = new SimpleGroup("Roles");

    Principal p = null;/*from   www  .j  av  a2  s.  c o m*/

    String certPrincipal = getUsername();

    try {
        initializeRolesProvider();

        LOGGER.debug("Certificate principal:" + certPrincipal);

        String searchName = environment.getLDAPAttribute(certPrincipal, UID);
        if (StringUtils.isBlank(searchName)) {
            throw new LoginException("A certificate with a UID attribute in the subject name is required.");
        }

        environment.validate(certPrincipal);

        Collection<String> groupNames = rolesProvider.getUserRoles(searchName);

        p = super.createIdentity(roleName);

        userRoles.addMember(p);
        for (String groupName : groupNames) {
            Principal role = super.createIdentity(groupName);
            LOGGER.debug("Found role: " + groupName);
            userRoles.addMember(role);
        }

        if (ACCESS_LOGGER.isDebugEnabled()) {
            ACCESS_LOGGER.debug("Certificate principal: " + certPrincipal + ", roles: "
                    + Arrays.toString(groupNames.toArray()));
        }

        LOGGER.debug("Assign principal [" + p.getName() + "] to role [" + roleName + "]");
    } catch (Exception e) {
        String principalName = p == null ? certPrincipal : p.getName();
        LOGGER.error("Failed to assign principal [" + principalName + "] to role [" + roleName + "]", e);
    }
    Group[] roleSets = { userRoles };
    return roleSets;
}

From source file:org.jboss.datavirt.commons.auth.jboss7.SAMLBearerTokenLoginModule.java

/**
 * Gets the key pair to use to validate the assertion's signature.  The key pair is retrieved
 * from the keystore.//from   w ww  .  j av  a 2 s  .  co  m
 * @param assertion
 * @throws LoginException
 */
private KeyPair getKeyPair(AssertionType assertion) throws LoginException {
    KeyStore keystore = loadKeystore();
    try {
        return SAMLBearerTokenUtil.getKeyPair(keystore, keyAlias, keyPassword);
    } catch (Exception e) {
        e.printStackTrace();
        throw new LoginException(
                "Failed to get KeyPair when validating SAML assertion signature.  Alias: " + keyAlias);
    }
}

From source file:io.hops.hopsworks.api.user.AuthService.java

@POST
@Path("ldapLogin")
@Produces(MediaType.APPLICATION_JSON)/* www. ja v a2  s.co  m*/
public Response ldapLogin(@FormParam("username") String username, @FormParam("password") String password,
        @FormParam("chosenEmail") String chosenEmail, @FormParam("consent") boolean consent,
        @Context HttpServletRequest req) throws LoginException, UserException {
    RESTApiJsonResponse json = new RESTApiJsonResponse();
    if (username == null || username.isEmpty()) {
        throw new IllegalArgumentException("Username can not be empty.");
    }
    if (password == null || password.isEmpty()) {
        throw new IllegalArgumentException("Password can not be empty.");
    }
    LdapUserState ldapUserState = ldapUserController.login(username, password, consent, chosenEmail);
    if (!ldapUserState.isSaved()) {
        return Response.status(Response.Status.PRECONDITION_FAILED).entity(ldapUserState.getUserDTO()).build();
    }
    LdapUser ladpUser = ldapUserState.getLdapUser();
    if (ladpUser == null || ladpUser.getUid() == null) {
        throw new LoginException("Failed to get ldap user from table.");
    }
    Users user = ladpUser.getUid();
    // Do pre cauth realm check 
    String passwordWithSalt = authController.preLdapLoginCheck(user, ladpUser.getAuthKey());
    if (req.getRemoteUser() != null && !req.getRemoteUser().equals(user.getEmail())) {
        logoutAndInvalidateSession(req);
    }
    //only login if not already logged...
    if (req.getRemoteUser() == null) {
        login(user, user.getEmail(), passwordWithSalt, req);
    } else {
        req.getServletContext().log("Skip logged because already logged in: " + username);
    }
    //read the user data from db and return to caller
    json.setSessionID(req.getSession().getId());
    json.setData(user.getEmail());
    return Response.status(Response.Status.OK).entity(json).build();
}

From source file:edu.vt.middleware.ldap.jaas.AbstractLoginModule.java

/** {@inheritDoc} */
public boolean commit() throws LoginException {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Begin commit");
    }/*from  ww  w  . j a  v a  2 s  .c om*/
    if (!this.loginSuccess) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Login failed");
        }
        return false;
    }

    if (this.subject.isReadOnly()) {
        this.clearState();
        throw new LoginException("Subject is read-only.");
    }
    this.subject.getPrincipals().addAll(this.principals);
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Committed the following principals: " + this.principals);
    }
    this.subject.getPrivateCredentials().addAll(this.credentials);
    this.subject.getPrincipals().addAll(this.roles);
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Committed the following roles: " + this.roles);
    }
    if (this.principalGroupName != null) {
        final LdapGroup group = new LdapGroup(this.principalGroupName);
        for (Principal principal : this.principals) {
            group.addMember(principal);
        }
        subject.getPrincipals().add(group);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Committed the following principal group: " + group);
        }
    }
    if (this.roleGroupName != null) {
        final LdapGroup group = new LdapGroup(this.roleGroupName);
        for (Principal role : this.roles) {
            group.addMember(role);
        }
        subject.getPrincipals().add(group);
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Committed the following role group: " + group);
        }
    }

    this.clearState();
    this.commitSuccess = true;
    return true;
}