List of usage examples for javax.security.auth.login LoginException LoginException
public LoginException(String msg)
From source file:org.transdroid.search.ScambioEtico.ScambioEtico.java
private DefaultHttpClient prepareRequest(Context context) throws Exception { String username = SettingsHelper.getSiteUser(context, TorrentSite.ScambioEtico); String password = SettingsHelper.getSitePass(context, TorrentSite.ScambioEtico); if (username == null || password == null) { throw new InvalidParameterException( "No username or password was provided, while " + "this is required for Scambio Etico."); }//from w w w . ja v a 2s .c o m // Setup request using GET HttpParams httpparams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT); DefaultHttpClient httpclient = new DefaultHttpClient(httpparams); // First log in Log.d("ScambioEtico", "Starting Authentication"); HttpPost loginPost = new HttpPost(LOGINURL); loginPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair[] { new BasicNameValuePair(LOGIN_USER, username), new BasicNameValuePair(LOGIN_PASS, password) }))); HttpResponse loginResult = httpclient.execute(loginPost); String loginHtml = HttpHelper.convertStreamToString(loginResult.getEntity().getContent()); if (loginHtml.indexOf(WRONG_LOGIN) >= 0) { throw new LoginException("Login failure for Scambio Etico wrong username " + username); } else if (loginHtml.indexOf(WRONG_PASSWORD) >= 0) { throw new LoginException("Login failure for Scambio Etico: bad password for user " + username); } Log.d("ScambioEtico", "Authentication successful"); return httpclient; }
From source file:ddf.ldap.ldaplogin.SslLdapLoginModule.java
protected boolean doLogin() throws LoginException { // --------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP ------------- Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username: "); callbacks[1] = new PasswordCallback("Password: ", false); try {/*from www . ja v a2 s . co m*/ callbackHandler.handle(callbacks); } catch (IOException ioException) { LOGGER.debug("Exception while handling login.", ioException); throw new LoginException(ioException.getMessage()); } catch (UnsupportedCallbackException unsupportedCallbackException) { LOGGER.debug("Exception while handling login.", unsupportedCallbackException); throw new LoginException( unsupportedCallbackException.getMessage() + " not available to obtain information from user."); } user = ((NameCallback) callbacks[0]).getName(); if (user == null) { return false; } user = user.trim(); validateUsername(user); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); // If either a username or password is specified don't allow authentication = "none". // This is to prevent someone from logging into Karaf as any user without providing a // valid password (because if authentication = none, the password could be any // value - it is ignored). // Username is not checked in this conditional because a null username immediately exits // this method. if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) { LOGGER.debug("Changing from authentication = none to simple since user or password was specified."); // default to simple so that the provided user/password will get checked setBindMethod(DEFAULT_AUTHENTICATION); } if (tmpPassword == null) { tmpPassword = new char[0]; } // --------------------------------------------------------------------- // RESET OBJECT STATE AND DECLARE LOCAL VARS principals = new HashSet<>(); Connection connection; String userDn; // --------------------------------------------------------------------- // ------------- CREATE CONNECTION #1 ---------------------------------- try { connection = ldapConnectionPool.borrowObject(); } catch (Exception e) { LOGGER.info("Unable to obtain ldap connection from pool", e); return false; } try { if (connection != null) { // ------------- BIND #1 (CONNECTION USERNAME & PASSWORD) -------------- try { BindRequest request; switch (bindMethod) { case "Simple": request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword); break; case "SASL": request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword); break; case "GSSAPI SASL": request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword); ((GSSAPISASLBindRequest) request).setRealm(realm); ((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress); break; case "Digest MD5 SASL": request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword); ((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH); ((DigestMD5SASLBindRequest) request).getQOPs().clear(); ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF); ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT); ((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH); if (StringUtils.isNotEmpty(realm)) { ((DigestMD5SASLBindRequest) request).setRealm(realm); } break; default: request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword); break; } LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername); BindResult bindResult = connection.bind(request); if (!bindResult.isSuccess()) { LOGGER.debug("Bind failed"); return false; } } catch (LdapException e) { LOGGER.debug("Unable to bind to LDAP server.", e); return false; } LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername); // --------- SEARCH #1, FIND USER DISTINGUISHED NAME ----------- SearchScope scope; scope = userSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL; userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user)); userFilter = userFilter.replace("\\", "\\\\"); LOGGER.trace("Performing LDAP query for user: {} at {} with filter {}", user, userBaseDN, userFilter); try (ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter)) { while (entryReader.hasNext() && entryReader.isReference()) { LOGGER.debug("Referral ignored while searching for user {}", user); entryReader.readReference(); } if (!entryReader.hasNext()) { LOGGER.info("User {} not found in LDAP.", user); return false; } SearchResultEntry searchResultEntry = entryReader.readEntry(); userDn = searchResultEntry.getName().toString(); } catch (LdapException | SearchResultReferenceIOException e) { LOGGER.info("Unable to read contents of LDAP user search.", e); return false; } // ----- BIND #2 (USER DISTINGUISHED NAME AND PASSWORD) ------------ // Validate user's credentials. try { LOGGER.trace("Attempting LDAP bind for user: {}", userDn); BindResult bindResult = connection.bind(userDn, tmpPassword); if (!bindResult.isSuccess()) { LOGGER.info("Bind failed"); return false; } } catch (Exception e) { LOGGER.info("Unable to bind user: {} to LDAP server.", userDn, e); return false; } LOGGER.trace("LDAP bind successful for user: {}", userDn); // ---------- ADD USER AS PRINCIPAL -------------------------------- principals.add(new UserPrincipal(user)); // ----- BIND #3 (CONNECTION USERNAME & PASSWORD) -------------- try { LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername); BindResult bindResult = connection.bind(connectionUsername, connectionPassword); if (!bindResult.isSuccess()) { LOGGER.info("Bind failed"); return false; } } catch (LdapException e) { LOGGER.info("Unable to bind to LDAP server.", e); return false; } LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername); // --------- SEARCH #3, GET ROLES ------------------------------ scope = roleSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL; roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user)); roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN)); roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn)); roleFilter = roleFilter.replace("\\", "\\\\"); LOGGER.trace( "Performing LDAP query for roles for user: {} at {} with filter {} for role attribute {}", user, roleBaseDN, roleFilter, roleNameAttribute); // ------------- ADD ROLES AS NEW PRINCIPALS ------------------- try (ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute)) { SearchResultEntry entry; while (entryReader.hasNext()) { if (entryReader.isEntry()) { entry = entryReader.readEntry(); Attribute attr = entry.getAttribute(roleNameAttribute); if (attr == null) { throw new LoginException("No attributes returned for [" + roleNameAttribute + " : " + roleBaseDN + "]"); } for (ByteString role : attr) { principals.add(new RolePrincipal(role.toString())); } } else { // Got a continuation reference. final SearchResultReference ref = entryReader.readReference(); LOGGER.debug("Skipping result reference: {}", ref.getURIs()); } } } catch (Exception e) { LOGGER.debug("Exception while getting roles for [" + user + "].", e); throw new LoginException("Can't get roles for [" + user + "]: " + e.getMessage()); } } else { LOGGER.trace("LDAP Connection was null could not authenticate user."); return false; } return true; } finally { ldapConnectionPool.returnObject(connection); } }
From source file:org.apache.ranger.authentication.unix.jaas.PamLoginModule.java
@Override public boolean logout() throws LoginException { if (_subject.isReadOnly()) { cleanup();// w w w . j a v a 2 s . c om throw new LoginException("Subject is read-only"); } _subject.getPrincipals().remove(_principal); cleanup(); return true; }
From source file:com.vmware.identity.idm.server.provider.localos.LocalOsIdentityProvider.java
@Override public PrincipalId authenticate(PrincipalId principal, String password) throws LoginException { this.validatePrincipal(principal); ValidateUtil.validateNotNull(password, "password"); principal = ServerUtils.normalizeAliasInPrincipal(principal, this.getDomain(), this.getAlias()); IOsSamAdapter samAdapter = getSamAdapter(); try {//from w w w.j a v a2 s . c om samAdapter.LogonUser(principal.getName(), password); return ServerUtils.getPrincipalId(null, principal.getName(), this.getDomainName()); } catch (Exception ex) { throw new LoginException(ex.getMessage()); } }
From source file:org.overlord.security.eval.jaxrs.auth.SAMLBearerTokenLoginModule.java
/** * Validates that the assertion is acceptable based on configurable criteria. * @param assertion//from w w w . j ava2s. c o m * @param request * @throws LoginException */ private boolean validateAssertion(AssertionType assertion, HttpServletRequest request) throws LoginException { // Possibly fail the assertion based on issuer. String issuer = assertion.getIssuer().getValue(); if (!issuer.equals(expectedIssuer)) { throw new LoginException("Unexpected SAML Assertion Issuer: " + issuer); } // Possibly fail the assertion based on audience restriction String currentAudience = request.getContextPath(); Set<String> audienceRestrictions = getAudienceRestrictions(assertion); if (!audienceRestrictions.contains(currentAudience)) { throw new LoginException( "SAML Assertion Audience Restrictions not valid for this context (" + currentAudience + ")"); } // Possibly fail the assertion based on time. Date now = new Date(); ConditionsType conditions = assertion.getConditions(); Date notBefore = conditions.getNotBefore().toGregorianCalendar().getTime(); Date notOnOrAfter = conditions.getNotOnOrAfter().toGregorianCalendar().getTime(); if (now.compareTo(notBefore) == -1) { throw new LoginException("SAML Assertion not yet valid."); } if (now.compareTo(notOnOrAfter) >= 0) { throw new LoginException("SAML Assertion no longer valid."); } return true; }
From source file:org.gatein.sso.saml.plugin.SAML2IdpLoginModule.java
public boolean login() throws LoginException { try {/*from w w w .j av a 2 s.com*/ Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("Username"); callbacks[1] = new PasswordCallback("Password", false); callbackHandler.handle(callbacks); String username = ((NameCallback) callbacks[0]).getName(); String password = new String(((PasswordCallback) callbacks[1]).getPassword()); ((PasswordCallback) callbacks[1]).clearPassword(); if (username == null || password == null) { return false; } boolean authenticationSuccess = validateUser(username, password); if (authenticationSuccess) { log.debug("Successful REST login request for authentication of user " + username); sharedState.put("javax.security.auth.login.name", username); return true; } else { String message = "Remote login via REST failed for username " + username; log.warn(message); throw new LoginException(message); } } catch (LoginException le) { throw le; } catch (Exception e) { log.warn("Exception during login: " + e.getMessage(), e); throw new LoginException(e.getMessage()); } }
From source file:com.flexive.core.security.FxDefaultLogin.java
/** * Abstract method to commit the authentication process (phase 2). * <p/>/*w w w. j a v a2 s.co m*/ * This method is called if the LoginContext's overall authentication succeeded * (the relevant REQUIRED, REQUISITE, SUFFICIENT and OPTIONAL LoginModules succeeded). * <p/> * If this LoginModule's own authentication attempt succeeded (checked by retrieving the private state saved by the * <code>login</code> method), then this method associates a <code>RdbmsPrincipal</code> * with the <code>Subject</code> located in the * <code>LoginModule</code>. If this LoginModule's own * authentication attempted failed, then this method removes * any state that was originally saved. * * @return true if this LoginModule's own login and commit attempts succeeded, or false otherwise. * @throws LoginException if the commit fails */ @Override public boolean commit() throws LoginException { if (success) { // Subject may not be read only if (subject.isReadOnly()) { LoginException le = new LoginException("Subject is Readonly"); LOG.error(le); throw le; } // Set the principials and credentials subject.getPrincipals().addAll(tempPrincipals); //subject.getPublicCredentials().add(tempUserTicket); } // Clear all temp variables clearTemporaryStates(); return true; }
From source file:de.adorsys.oauth.loginmodule.HTTPAuthenticationLoginModule.java
private boolean authenticate(String username, String password) throws LoginException { HttpHost targetHost = new HttpHost(restEndpoint.getHost(), restEndpoint.getPort(), restEndpoint.getScheme());// w w w .j av a 2 s .co m CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(Consts.UTF_8); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); HttpGet httpGet = new HttpGet(restEndpoint); CloseableHttpResponse userInfoResponse = null; try { userInfoResponse = HTTP_CLIENT.execute(httpGet, context); if (userInfoResponse.getStatusLine().getStatusCode() != 200) { LOG.error("Authentication failed for user {}, restEndpoint {} HTTP Status {}", username, restEndpoint.toASCIIString(), userInfoResponse.getStatusLine()); throw new LoginException("Authentication failed for user " + username + ", restEndpoint " + restEndpoint.toASCIIString() + " HTTP Status " + userInfoResponse.getStatusLine()); } String userInfoJson = readUserInfo(userInfoResponse); JSONObject userInfo = new JSONObject(userInfoJson); String principalId = userInfo.getString("principal"); if (principalId == null) { LOG.error("could not read field 'principal' for user {}. Response: {}", username, userInfoJson); throw new LoginException( "could not read field 'principal' for user " + username + ". Response: " + userInfoJson); } JSONArray roles = userInfo.getJSONArray("roles"); populateSubject(principalId, roles); // we put them to shared stated that other login providers can also // authenticate sharedState.put("javax.security.auth.login.name", principalId); sharedState.put("javax.security.auth.login.password", password); } catch (IOException e) { throw new IllegalStateException("problem on http backend authentication", e); } finally { if (userInfoResponse != null) { try { userInfoResponse.close(); } catch (IOException e) { ; // NOOP } } } return true; }
From source file:net.dv8tion.jda.core.entities.impl.JDAImpl.java
public void login(String token, ShardInfo shardInfo) throws LoginException, RateLimitedException { setStatus(Status.LOGGING_IN);/*w w w . ja v a2 s. c om*/ if (token == null || token.isEmpty()) throw new LoginException("Provided token was null or empty!"); setToken(token); verifyToken(); this.shardInfo = shardInfo; LOG.info("Login Successful!"); client = new WebSocketClient(this); if (shutdownHook != null) { Runtime.getRuntime().addShutdownHook(shutdownHook); } }
From source file:org.jboss.datavirt.commons.auth.jboss7.SAMLBearerTokenLoginModule.java
/** * @see org.jboss.security.auth.spi.AbstractServerLoginModule#login() *//*from ww w . jav a2 s. c o m*/ @Override public boolean login() throws LoginException { try { HttpServletRequest request = getCurrentRequest(); String authorization = request.getHeader("Authorization"); if (authorization != null && authorization.startsWith("Basic")) { String b64Data = authorization.substring(6); byte[] dataBytes = Base64.decodeBase64(b64Data); String data = new String(dataBytes, "UTF-8"); if (data.startsWith("SAML-BEARER-TOKEN:")) { String assertionData = data.substring(18); Document samlAssertion = DocumentUtil.getDocument(assertionData); SAMLAssertionParser parser = new SAMLAssertionParser(); DOMSource source = new DOMSource(samlAssertion); XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(source); Object parsed = parser.parse(xmlEventReader); AssertionType assertion = (AssertionType) parsed; SAMLBearerTokenUtil.validateAssertion(assertion, request, allowedIssuers); if ("true".equals(signatureRequired)) { KeyPair keyPair = getKeyPair(assertion); if (!SAMLBearerTokenUtil.isSAMLAssertionSignatureValid(samlAssertion, keyPair)) { throw new LoginException("Invalid signature found on SAML assertion!"); } } consumeAssertion(assertion); loginOk = true; return true; } } } catch (LoginException le) { throw le; } catch (Exception e) { e.printStackTrace(); loginOk = false; return false; } return super.login(); }