Java Examples for javax.security.auth.login.FailedLoginException
The following java examples will help you to understand the usage of javax.security.auth.login.FailedLoginException. These source code samples are taken from different open source projects.
Example 1
Project: btpka3.github.com-master File: SimpleTestUsernamePasswordAuthenticationHandler.java View source code |
@Override protected HandlerResult authenticateUsernamePasswordInternal(UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException { final String username = credential.getUsername(); final String password = credential.getPassword(); if (!StringUtils.hasText(username)) { throw new AccountNotFoundException("username can not be blank."); } if (!StringUtils.hasText(password)) { throw new FailedLoginException("password can not be blank."); } if (!username.equals(password)) { throw new FailedLoginException("password is not equal with username."); } return createHandlerResult(credential, new SimplePrincipal(username), null); }
Example 2
Project: cas-master File: LdapAuthenticationHandler.java View source code |
@Override
protected HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential upc, final String originalPassword) throws GeneralSecurityException, PreventedException {
final AuthenticationResponse response;
try {
LOGGER.debug("Attempting LDAP authentication for [{}]. Authenticator pre-configured attributes are [{}], " + "additional requested attributes for this authentication request are [{}]", upc, authenticator.getReturnAttributes(), authenticatedEntryAttributes);
final AuthenticationRequest request = new AuthenticationRequest(upc.getUsername(), new org.ldaptive.Credential(upc.getPassword()), authenticatedEntryAttributes);
response = authenticator.authenticate(request);
} catch (final LdapException e) {
LOGGER.trace(e.getMessage(), e);
throw new PreventedException("Unexpected LDAP error", e);
}
LOGGER.debug("LDAP response: [{}]", response);
final List<MessageDescriptor> messageList;
final LdapPasswordPolicyConfiguration ldapPasswordPolicyConfiguration = (LdapPasswordPolicyConfiguration) super.getPasswordPolicyConfiguration();
if (ldapPasswordPolicyConfiguration != null) {
LOGGER.debug("Applying password policy to [{}]", response);
messageList = ldapPasswordPolicyConfiguration.getAccountStateHandler().handle(response, ldapPasswordPolicyConfiguration);
} else {
LOGGER.debug("No ldap password policy configuration is defined");
messageList = Collections.emptyList();
}
if (response.getResult()) {
LOGGER.debug("LDAP response returned a result. Creating the final LDAP principal");
return createHandlerResult(upc, createPrincipal(upc.getUsername(), response.getLdapEntry()), messageList);
}
if (AuthenticationResultCode.DN_RESOLUTION_FAILURE == response.getAuthenticationResultCode()) {
LOGGER.warn("DN resolution failed. [{}]", response.getMessage());
throw new AccountNotFoundException(upc.getUsername() + " not found.");
}
throw new FailedLoginException("Invalid credentials");
}
Example 3
Project: jWSMV-master File: Port.java View source code |
public Object dispatch(String action, List<Object> headers, Object input) throws IOException, HTTPException, JAXBException, FaultException, FailedLoginException {
Unmarshaller unmarshaller = JAXB.createUnmarshaller();
Marshaller marshaller = JAXB.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
Header header = Factories.SOAP.createHeader();
AttributedURI to = Factories.ADDRESS.createAttributedURI();
to.setValue(url);
to.getOtherAttributes().put(MUST_UNDERSTAND, "true");
header.getAny().add(Factories.ADDRESS.createTo(to));
EndpointReferenceType endpointRef = Factories.ADDRESS.createEndpointReferenceType();
AttributedURI address = Factories.ADDRESS.createAttributedURI();
address.setValue(REPLY_TO);
address.getOtherAttributes().put(MUST_UNDERSTAND, "true");
endpointRef.setAddress(address);
header.getAny().add(Factories.ADDRESS.createReplyTo(endpointRef));
AttributedURI soapAction = Factories.ADDRESS.createAttributedURI();
soapAction.setValue(action);
soapAction.getOtherAttributes().put(MUST_UNDERSTAND, "true");
header.getAny().add(Factories.ADDRESS.createAction(soapAction));
AttributedURI messageId = Factories.ADDRESS.createAttributedURI();
messageId.setValue("uuid:" + UUID.randomUUID().toString().toUpperCase());
header.getAny().add(Factories.ADDRESS.createMessageID(messageId));
for (Object obj : headers) {
header.getAny().add(obj);
}
Locale locale = Factories.WSMAN.createLocale();
locale.setLang("en-US");
locale.getOtherAttributes().put(MUST_UNDERSTAND, "false");
header.getAny().add(locale);
//
if (input instanceof AnyXmlType) {
input = ((AnyXmlType) input).getAny();
} else if (input instanceof AnyXmlOptionalType) {
input = ((AnyXmlOptionalType) input).getAny();
}
Body body = Factories.SOAP.createBody();
if (input != null) {
body.getAny().add(input);
}
Envelope request = Factories.SOAP.createEnvelope();
request.setHeader(header);
request.setBody(body);
URL u = new URL(url);
boolean retry = false;
Object result = null;
HttpURLConnection conn = null;
do {
try {
if (conn != null) {
conn.disconnect();
}
logger.trace(Message.STATUS_CONNECT, url, scheme);
switch(scheme) {
case NONE:
switch(proxy.type()) {
case DIRECT:
conn = (HttpURLConnection) u.openConnection();
break;
default:
conn = (HttpURLConnection) u.openConnection(proxy);
break;
}
break;
case NTLM:
conn = NtlmHttpURLConnection.openConnection(u, cred, encrypt);
((NtlmHttpURLConnection) conn).setProxy(proxy, proxyCred);
break;
case BASIC:
switch(proxy.type()) {
case DIRECT:
conn = (HttpURLConnection) u.openConnection();
break;
default:
conn = (HttpURLConnection) u.openConnection(proxy);
if (proxyCred != null) {
String clear = proxyCred.getUserName() + ":" + new String(proxyCred.getPassword());
String auth = "Basic " + Base64.encodeBytes(clear.getBytes());
conn.setRequestProperty("Proxy-Authorization", auth);
}
break;
}
break;
}
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/soap+xml;charset=UTF-8");
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
marshaller.marshal(Factories.SOAP.createEnvelope(request), buffer);
byte[] bytes = buffer.toByteArray();
conn.setFixedLengthStreamingMode(bytes.length);
conn.connect();
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.flush();
logger.debug(Message.STATUS_REQUEST, action);
if (debug != null) {
StringBuffer sb = new StringBuffer("[").append(new Date().toString()).append("] - SOAP Request:\r\n");
debug.write(sb.toString().getBytes());
debug.write(bytes);
debug.write("\r\n".getBytes());
debug.flush();
}
retry = false;
int code = conn.getResponseCode();
switch(code) {
case HttpURLConnection.HTTP_INTERNAL_ERROR:
result = getSOAPBodyContents(unmarshaller, marshaller, conn.getErrorStream(), conn.getContentType());
break;
case HttpURLConnection.HTTP_OK:
result = getSOAPBodyContents(unmarshaller, marshaller, conn.getInputStream(), conn.getContentType());
break;
case HttpURLConnection.HTTP_UNAUTHORIZED:
retry = true;
break;
default:
logger.warn(Message.ERROR_RESPONSE, code);
debug(conn);
throw new HTTPException(code);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
} while (retry && nextAuthScheme(conn));
if (result instanceof JAXBElement) {
result = ((JAXBElement) result).getValue();
}
logger.debug(Message.STATUS_RESPONSE, result == null ? "null" : result.getClass().getName());
if (result instanceof Fault) {
throw new FaultException((Fault) result);
} else {
return result;
}
}
Example 4
Project: simba-os-master File: ActiveDirectoryLoginModule.java View source code |
@Override protected boolean verifyLoginData() throws FailedLoginException { String[] returnedAtts = { authenticationAttribute }; Encoder encoder = DefaultEncoder.getInstance(); String requestSearchFilter = searchFilter.replaceAll("%USERNAME%", encoder.encodeForLDAP(getUsername())); SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); searchCtls.setSearchScope(searchScope); Hashtable<String, String> env = getEnv(); debug("Verifying credentials for user: " + getUsername()); boolean ldapUser = false; String userCN = null; try { LdapContext ldapContext = getLdapContext(env); if (ldapContext != null) { NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, requestSearchFilter, searchCtls); while (!ldapUser && answer.hasMoreElements()) { SearchResult sr = answer.next(); userCN = sr.getName(); Attributes attrs = sr.getAttributes(); if (attrs != null) { NamingEnumeration<? extends Attribute> ne = attrs.getAll(); ldapUser = ne.hasMore(); ne.close(); } } debug("Authentication succeeded"); if (Boolean.TRUE.equals(GlobalContext.locate(ConfigurationService.class).getValue(SimbaConfigurationParameter.ENABLE_AD_GROUPS)) && userCN != null) { updateUserGroups(ldapContext, userCN); } } return ldapUser; } catch (NamingException ex) { debug("Authentication failed"); throw new FailedLoginException(ex.getMessage()); } }
Example 5
Project: tomee-master File: SQLLoginModule.java View source code |
/** * This LoginModule is not to be ignored. So, this method should never * return false. * * @return true if authentication succeeds, or throw a LoginException such * as FailedLoginException if authentication fails */ public boolean login() throws LoginException { loginSucceeded = false; final Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("User name"); callbacks[1] = new PasswordCallback("Password", false); try { handler.handle(callbacks); } catch (final IOExceptionUnsupportedCallbackException | ioe) { throw (LoginException) new LoginException().initCause(ioe); } assert callbacks.length == 2; cbUsername = ((NameCallback) callbacks[0]).getName(); if (Strings.checkNullBlankString(cbUsername)) { throw new FailedLoginException(); } final char[] provided = ((PasswordCallback) callbacks[1]).getPassword(); cbPassword = provided == null ? null : new String(provided); try { final Connection conn; if (dataSource != null) { conn = dataSource.getConnection(); } else if (driver != null) { conn = driver.connect(connectionURL, properties); } else { conn = DriverManager.getConnection(connectionURL, properties); } try { PreparedStatement statement = conn.prepareStatement(userSelect); try { final int count = statement.getParameterMetaData().getParameterCount(); for (int i = 0; i < count; i++) { statement.setObject(i + 1, cbUsername); } final ResultSet result = statement.executeQuery(); try { boolean found = false; while (result.next()) { final String userName = result.getString(1); final String userPassword = result.getString(2); if (cbUsername.equals(userName)) { found = true; if (!checkPassword(userPassword, cbPassword)) { throw new FailedLoginException(); } break; } } if (!found) { // User does not exist throw new FailedLoginException(); } } finally { result.close(); } } finally { statement.close(); } statement = conn.prepareStatement(groupSelect); try { final int count = statement.getParameterMetaData().getParameterCount(); for (int i = 0; i < count; i++) { statement.setObject(i + 1, cbUsername); } final ResultSet result = statement.executeQuery(); try { while (result.next()) { final String userName = result.getString(1); final String groupName = result.getString(2); if (cbUsername.equals(userName)) { groups.add(groupName); } } } finally { result.close(); } } finally { statement.close(); } } finally { conn.close(); } } catch (final LoginException e) { cbUsername = null; cbPassword = null; groups.clear(); throw e; } catch (final SQLException sqle) { cbUsername = null; cbPassword = null; groups.clear(); throw (LoginException) new LoginException("SQL error").initCause(sqle); } catch (final Exception e) { cbUsername = null; cbPassword = null; groups.clear(); throw (LoginException) new LoginException("Could not access datasource").initCause(e); } loginSucceeded = true; return true; }
Example 6
Project: cas-server-4.0.1-master File: X509CredentialsAuthenticationHandler.java View source code |
/** {@inheritDoc} */
@Override
protected final HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
final X509CertificateCredential x509Credential = (X509CertificateCredential) credential;
final X509Certificate[] certificates = x509Credential.getCertificates();
X509Certificate clientCert = null;
boolean hasTrustedIssuer = false;
for (int i = certificates.length - 1; i >= 0; i--) {
final X509Certificate certificate = certificates[i];
logger.debug("Evaluating {}", CertUtils.toString(certificate));
validate(certificate);
if (!hasTrustedIssuer) {
hasTrustedIssuer = isCertificateFromTrustedIssuer(certificate);
}
// getBasicConstraints returns pathLenContraint which is generally
// >=0 when this is a CA cert and -1 when it's not
int pathLength = certificate.getBasicConstraints();
if (pathLength < 0) {
logger.debug("Found valid client certificate");
clientCert = certificate;
} else {
logger.debug("Found valid CA certificate");
}
}
if (hasTrustedIssuer && clientCert != null) {
x509Credential.setCertificate(clientCert);
return new HandlerResult(this, x509Credential, new SimplePrincipal(x509Credential.getId()));
}
throw new FailedLoginException();
}
Example 7
Project: HealtheMe-master File: PHRLogin.java View source code |
/* * Custom realm implementation:only the following * method need to be implemented. * */ protected void authenticateUser() throws LoginException, FailedLoginException { // Get the current realm and check whether it is instance of your realm if (!(_currentRealm instanceof PHRRealm)) { throw new LoginException("PHRRealm : Bad Realm"); } PHRRealm realm = (PHRRealm) _currentRealm; String[] grpList = realm.authenticateUser(_username, _password); if (grpList == null) { // JAAS behavior throw new FailedLoginException("PHRRealm : Login Failed/Inactive with user " + _username); } else if (grpList.length > 0 && grpList[0].equalsIgnoreCase(realm.getLockedRole())) { throw new AccountLockedException("PHRRealm : Login Locked for user " + _username); } log("login succeeded for " + _username); // Add the code related to authenticating to your user database. String[] groupListToForward = (String[]) grpList.clone(); /* * Call the commitAuthentication to populate * grpList with the set of groups to which * _username belongs in this realm. */ /* commitUserAuthentication(_username, _password, _currentRealm, groupListToForward); */ commitUserAuthentication(groupListToForward); }
Example 8
Project: ISTIC_M2GL-master File: ChatRoomImpl.java View source code |
public boolean authentification(String username, char[] password) throws FailedLoginException, RemoteException { // verify the username/password boolean usernameCorrect = false; boolean passwordCorrect = false; if (this.alloweduser.containsKey(username)) { usernameCorrect = true; if (password.length == this.alloweduser.get(username).length && testPassword(this.alloweduser.get(username), password)) { // authentication succeeded!!! passwordCorrect = true; if (debug) System.out.println("\t\t[SampleLoginModule] " + "authentication succeeded"); return true; } } // authentication failed -- clean out state if (debug) System.out.println("\t\t[SampleLoginModule] " + "authentication failed"); for (int i = 0; i < password.length; i++) password[i] = ' '; if (!usernameCorrect) { throw new FailedLoginException("User Name Incorrect"); } else { throw new FailedLoginException("Password Incorrect"); } }
Example 9
Project: marketcetera-master File: ClientLoginModuleTest.java View source code |
/** * Test login success & failures. * @throws Exception if there was failure */ @Test public void loginTest() throws Exception { setLevel(ClientLoginModule.class.getName(), Level.INFO); //test failure conditions attemptLogin(null, getTestPassword(), AccountNotFoundException.class, Messages.EMPTY_USERNAME.getText()); attemptLogin("", getTestPassword(), AccountNotFoundException.class, Messages.EMPTY_USERNAME.getText()); final String u = randomString(); attemptLogin(u, getTestPassword(), FailedLoginException.class, Messages.USER_LOGIN_FAIL.getText(u)); assertLastEvent(Level.WARN, ClientLoginModule.class.getName(), Messages.USER_LOGIN_ERROR_LOG.getText(u), ClientLoginModule.class.getName()); attemptLogin(getTestUsername(), null, FailedLoginException.class, Messages.USER_LOGIN_FAIL.getText(getTestUsername())); assertLastEvent(Level.WARN, ClientLoginModule.class.getName(), Messages.USER_LOGIN_ERROR_LOG.getText(getTestUsername()), ClientLoginModule.class.getName()); attemptLogin(getTestUsername(), "".toCharArray(), FailedLoginException.class, Messages.USER_LOGIN_FAIL.getText(getTestUsername())); assertLastEvent(Level.WARN, ClientLoginModule.class.getName(), Messages.USER_LOGIN_ERROR_LOG.getText(getTestUsername()), ClientLoginModule.class.getName()); attemptLogin(getTestUsername(), randomString().toCharArray(), FailedLoginException.class, Messages.USER_LOGIN_FAIL.getText(getTestUsername())); assertLastEvent(Level.WARN, ClientLoginModule.class.getName(), Messages.USER_LOGIN_ERROR_LOG.getText(getTestUsername()), ClientLoginModule.class.getName()); //test failure due to client error I18NMessage0P fail = new I18NMessage0P(Messages.LOGGER, "testMessage"); sMockHelper.setFail(fail); attemptLogin(getTestUsername(), getTestPassword(), FailedLoginException.class, Messages.USER_LOGIN_ERROR.getText()); assertLastEvent(Level.WARN, ClientLoginModule.class.getName(), Messages.USER_LOGIN_ERROR_LOG.getText(getTestUsername()), ClientLoginModule.class.getName()); //test successful login sMockHelper.setFail(null); attemptLogin(getTestUsername(), getTestPassword(), null, null); assertLastEvent(Level.INFO, ClientLoginModule.class.getName(), Messages.USER_LOGIN_LOG.getText(getTestUsername()), ClientLoginModule.class.getName()); // test logout removes the principal from the subject loginContext.logout(); assertTrue(loginContext.getSubject().getPrincipals().isEmpty()); assertLastEvent(Level.INFO, ClientLoginModule.class.getName(), Messages.USER_LOGOUT_LOG.getText(getTestUsername()), ClientLoginModule.class.getName()); }
Example 10
Project: rj-core-master File: ServerAuthMethod.java View source code |
public final Client performLogin(final ServerLogin login) throws RjException, LoginException {
String client = null;
try {
client = getCallingClient();
if (login.getId() != this.pendingLoginId || !client.equals(this.pendingLoginClient)) {
throw new FailedLoginException("Login process was interrupted by another client.");
}
login.readAnswer(this.usePubkeyExchange ? this.pendingLoginKeyPair.getPrivate() : null);
this.pendingLoginKeyPair = null;
final String name = doPerformLogin(login.getCallbacks());
LOGGER.log(Level.INFO, "{0} performing login completed successfull: {1} ({2}).", new Object[] { this.logPrefix, name, client });
return new Client(name, getCallingClient(), (byte) 0);
} catch (final Exception e) {
if (e instanceof LoginException) {
final LogRecord log = new LogRecord(Level.INFO, "{0} performing login failed ({1}).");
log.setParameters(new Object[] { this.logPrefix, client });
log.setThrown(e);
LOGGER.log(log);
throw (LoginException) e;
}
if (e instanceof RjException) {
throw (RjException) e;
}
throw new RjException("An unexpected error occurred when validating the login credential.", e);
} finally {
System.gc();
}
}
Example 11
Project: shibboleth-idp-ext-cas-master File: AbstractProxyAuthenticator.java View source code |
@Override
public Void authenticate(@Nonnull final URI credential) throws GeneralSecurityException {
Constraint.isNotNull(credential, "URI to authenticate cannot be null.");
if (!HTTPS_SCHEME.equalsIgnoreCase(credential.getScheme())) {
throw new GeneralSecurityException(credential + " is not an https URI as required.");
}
final int status = authenticateProxyCallback(credential);
if (!allowedResponseCodes.contains(status)) {
throw new FailedLoginException(credential + " returned unacceptable HTTP status code " + status);
}
return null;
}
Example 12
Project: TeamCity-Crowd-Plugin-master File: CrowdLoginModule.java View source code |
@Override
public boolean login() throws LoginException {
try {
myCallbackHandler.handle(myCallbacks);
} catch (Exception e) {
throw new LoginException(e.toString());
}
final String username = myNameCallback.getName();
final String password = new String(myPasswordCallback.getPassword());
String message = String.format("Attempting to log in with user [%s]", username);
loggerFactory.getServerLogger().debug(message);
Optional<User> possiblyLoggedInUser = pluginCrowdClient.loginUserWithPassword(username, password);
if (possiblyLoggedInUser.isPresent()) {
mySubject.getPrincipals().add(loggedInUserService.updateMembership(possiblyLoggedInUser.get()));
return true;
}
throw new FailedLoginException("Invalid username or password");
}
Example 13
Project: activemq-artemis-master File: LDAPLoginModule.java View source code |
protected boolean authenticate(String username, String password) throws LoginException { MessageFormat userSearchMatchingFormat; boolean userSearchSubtreeBool; if (logger.isDebugEnabled()) { logger.debug("Create the LDAP initial context."); } try { openContext(); } catch (NamingException ne) { FailedLoginException ex = new FailedLoginException("Error opening LDAP connection"); ex.initCause(ne); throw ex; } if (!isLoginPropertySet(USER_SEARCH_MATCHING)) return false; userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING)); userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue(); try { String filter = userSearchMatchingFormat.format(new String[] { doRFC2254Encoding(username) }); SearchControls constraints = new SearchControls(); if (userSearchSubtreeBool) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } // setup attributes List<String> list = new ArrayList<>(); if (isLoginPropertySet(USER_ROLE_NAME)) { list.add(getLDAPPropertyValue(USER_ROLE_NAME)); } String[] attribs = new String[list.size()]; list.toArray(attribs); constraints.setReturningAttributes(attribs); if (logger.isDebugEnabled()) { logger.debug("Get the user DN."); logger.debug("Looking for the user in LDAP with "); logger.debug(" base DN: " + getLDAPPropertyValue(USER_BASE)); logger.debug(" filter: " + filter); } NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(USER_BASE), filter, constraints); if (results == null || !results.hasMore()) { throw new FailedLoginException("User " + username + " not found in LDAP."); } SearchResult result = results.next(); if (results.hasMore()) { // ignore for now } String dn; if (result.isRelative()) { logger.debug("LDAP returned a relative name: " + result.getName()); NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE)); Name entryName = parser.parse(result.getName()); Name name = contextName.addAll(baseName); name = name.addAll(entryName); dn = name.toString(); } else { logger.debug("LDAP returned an absolute name: " + result.getName()); try { URI uri = new URI(result.getName()); String path = uri.getPath(); if (path.startsWith("/")) { dn = path.substring(1); } else { dn = path; } } catch (URISyntaxException e) { closeContext(); FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI."); ex.initCause(e); throw ex; } } if (logger.isDebugEnabled()) { logger.debug("Using DN [" + dn + "] for binding."); } Attributes attrs = result.getAttributes(); if (attrs == null) { throw new FailedLoginException("User found, but LDAP entry malformed: " + username); } List<String> roles = null; if (isLoginPropertySet(USER_ROLE_NAME)) { roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles); } // check the credentials by binding to server if (bindUser(context, dn, password)) { // if authenticated add more roles roles = getRoles(context, dn, username, roles); if (logger.isDebugEnabled()) { logger.debug("Roles " + roles + " for user " + username); } for (String role : roles) { groups.add(new RolePrincipal(role)); } } else { throw new FailedLoginException("Password does not match for user: " + username); } } catch (CommunicationException e) { closeContext(); FailedLoginException ex = new FailedLoginException("Error contacting LDAP"); ex.initCause(e); throw ex; } catch (NamingException e) { closeContext(); FailedLoginException ex = new FailedLoginException("Error contacting LDAP"); ex.initCause(e); throw ex; } return true; }
Example 14
Project: activemq-master File: LDAPLoginModule.java View source code |
protected boolean authenticate(String username, String password) throws LoginException { MessageFormat userSearchMatchingFormat; boolean userSearchSubtreeBool; DirContext context = null; if (log.isDebugEnabled()) { log.debug("Create the LDAP initial context."); } try { context = open(); } catch (NamingException ne) { FailedLoginException ex = new FailedLoginException("Error opening LDAP connection"); ex.initCause(ne); throw ex; } if (!isLoginPropertySet(USER_SEARCH_MATCHING)) return false; userSearchMatchingFormat = new MessageFormat(getLDAPPropertyValue(USER_SEARCH_MATCHING)); userSearchSubtreeBool = Boolean.valueOf(getLDAPPropertyValue(USER_SEARCH_SUBTREE)).booleanValue(); try { String filter = userSearchMatchingFormat.format(new String[] { doRFC2254Encoding(username) }); SearchControls constraints = new SearchControls(); if (userSearchSubtreeBool) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } // setup attributes List<String> list = new ArrayList<String>(); if (isLoginPropertySet(USER_ROLE_NAME)) { list.add(getLDAPPropertyValue(USER_ROLE_NAME)); } String[] attribs = new String[list.size()]; list.toArray(attribs); constraints.setReturningAttributes(attribs); if (log.isDebugEnabled()) { log.debug("Get the user DN."); log.debug("Looking for the user in LDAP with "); log.debug(" base DN: " + getLDAPPropertyValue(USER_BASE)); log.debug(" filter: " + filter); } NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(USER_BASE), filter, constraints); if (results == null || !results.hasMore()) { log.warn("User " + username + " not found in LDAP."); throw new FailedLoginException("User " + username + " not found in LDAP."); } SearchResult result = results.next(); if (results.hasMore()) { // ignore for now } String dn; if (result.isRelative()) { log.debug("LDAP returned a relative name: {}", result.getName()); NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE)); Name entryName = parser.parse(result.getName()); Name name = contextName.addAll(baseName); name = name.addAll(entryName); dn = name.toString(); } else { log.debug("LDAP returned an absolute name: {}", result.getName()); try { URI uri = new URI(result.getName()); String path = uri.getPath(); if (path.startsWith("/")) { dn = path.substring(1); } else { dn = path; } } catch (URISyntaxException e) { if (context != null) { close(context); } FailedLoginException ex = new FailedLoginException("Error parsing absolute name as URI."); ex.initCause(e); throw ex; } } if (log.isDebugEnabled()) { log.debug("Using DN [" + dn + "] for binding."); } Attributes attrs = result.getAttributes(); if (attrs == null) { throw new FailedLoginException("User found, but LDAP entry malformed: " + username); } List<String> roles = null; if (isLoginPropertySet(USER_ROLE_NAME)) { roles = addAttributeValues(getLDAPPropertyValue(USER_ROLE_NAME), attrs, roles); } // check the credentials by binding to server if (bindUser(context, dn, password)) { // if authenticated add more roles roles = getRoles(context, dn, username, roles); if (log.isDebugEnabled()) { log.debug("Roles " + roles + " for user " + username); } for (int i = 0; i < roles.size(); i++) { groups.add(new GroupPrincipal(roles.get(i))); } } else { throw new FailedLoginException("Password does not match for user: " + username); } } catch (CommunicationException e) { FailedLoginException ex = new FailedLoginException("Error contacting LDAP"); ex.initCause(e); throw ex; } catch (NamingException e) { if (context != null) { close(context); } FailedLoginException ex = new FailedLoginException("Error contacting LDAP"); ex.initCause(e); throw ex; } return true; }
Example 15
Project: brix-cms-master File: ServerLoginModule.java View source code |
/**
* {@inheritDoc}
*/
public boolean login() throws LoginException {
try {
// clear any existing principals
principals.clear();
// authorize
Credentials credentials = getCredentials();
User user = authorizer.authorize(credentials, Role.WEBDAV, Role.RMI);
// store authorized principal
principals.add(new UserPrincipal(user.getLogin()));
return true;
} catch (AuthorizationException e) {
principals.clear();
throw new FailedLoginException(e.getMessage());
}
}
Example 16
Project: forgestore-master File: ShiroUTAuthorizingRealm.java View source code |
public boolean validate(UsernameToken usernameToken) throws LoginException { if (usernameToken == null) { throw new SecurityException("noCredential"); } // Validate the UsernameToken String pwType = usernameToken.getPasswordType(); logger.info("UsernameToken user " + usernameToken.getName()); logger.info("UsernameToken password " + usernameToken.getPassword()); logger.info("UsernameToken password type " + pwType); if (usernameToken.getPassword() == null) { logger.debug("Authentication failed - no password was provided"); throw new FailedLoginException("Sorry! No login for you."); } // Validate it via Shiro Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(usernameToken.getName(), usernameToken.getPassword()); token.setRememberMe(true); try { currentUser.login(token); } catch (AuthenticationException ex) { logger.info(ex.getMessage(), ex); throw new FailedLoginException("Sorry! No login for you."); } // Perform authorization check if (!requiredRoles.isEmpty() && !currentUser.hasAllRoles(requiredRoles)) { logger.info("Authorization failed for authenticated user"); throw new FailedLoginException("Sorry! No login for you."); } boolean succeeded = true; return succeeded; }
Example 17
Project: gatein-sso-master File: GateInAuthenticationHandler.java View source code |
@Override public HandlerResult authenticate(Credential credential) throws GeneralSecurityException, PreventedException { UsernamePasswordCredential usernamePasswordCredential = (UsernamePasswordCredential) credential; final String username = usernamePasswordCredential.getUsername(); final String password = usernamePasswordCredential.getPassword(); try { final boolean authenticated = getRestCallbackCaller().executeRemoteCall(username, password); if (authenticated) { return new HandlerResult(this, new BasicCredentialMetaData(usernamePasswordCredential), new SimplePrincipal(credential.getId())); } else { throw new FailedLoginException("Failed to login at GateIn with username " + username); } } catch (Exception e) { throw new FailedLoginException("Failed to login at GateIn. Cause: " + e.getMessage()); } }
Example 18
Project: geronimo-master File: TomcatGeronimoRealm.java View source code |
public Principal authenticate(CallbackHandler callbackHandler, String principalName) {
// Establish a LoginContext to use for authentication
try {
if ((principalName != null) && (!principalName.equals(""))) {
LoginContext loginContext = null;
if (appName == null)
appName = "Tomcat";
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.beginLogin", principalName, appName));
// What if the LoginModule is in the container class loader ?
ClassLoader ocl = null;
if (isUseContextClassLoader()) {
ocl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
try {
loginContext = new LoginContext(appName, callbackHandler);
} catch (Throwable e) {
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return (null);
} finally {
if (isUseContextClassLoader()) {
Thread.currentThread().setContextClassLoader(ocl);
}
}
if (log.isDebugEnabled())
log.debug("Login context created " + principalName);
// Negotiate a login via this LoginContext
Subject subject;
try {
loginContext.login();
Subject tempSubject = loginContext.getSubject();
if (tempSubject == null) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", principalName));
return (null);
}
subject = ContextManager.getServerSideSubject(tempSubject);
if (subject == null) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", principalName));
return (null);
}
ContextManager.setCurrentCaller(subject);
} catch (AccountExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.accountExpired", principalName));
return (null);
} catch (CredentialExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.credentialExpired", principalName));
return (null);
} catch (FailedLoginException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", principalName));
return (null);
} catch (LoginException e) {
log.warn(sm.getString("jaasRealm.loginException", principalName), e);
return (null);
} catch (Throwable e) {
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return (null);
}
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.loginContextCreated", principalName));
// Return the appropriate Principal for this authenticated Subject
/* Principal principal = createPrincipal(username, subject);
if (principal == null) {
log.debug(sm.getString("jaasRealm.authenticateFailure", username));
return (null);
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
}
*/
JAASTomcatPrincipal jaasPrincipal = new JAASTomcatPrincipal(principalName);
jaasPrincipal.setSubject(subject);
return (jaasPrincipal);
} else {
if (log.isDebugEnabled())
log.debug("Login Failed - null userID");
return null;
}
} catch (Throwable t) {
log.error("error ", t);
return null;
}
}
Example 19
Project: h2o-3-master File: PamLoginModule.java View source code |
private boolean performLogin() throws LoginException {
try {
UnixUser user = _pam.authenticate(_username, _password);
_principal = new PamPrincipal(user);
_authSucceeded = true;
return true;
} catch (PAMException ex) {
LoginException le = new FailedLoginException("Invalid username or password");
le.initCause(ex);
throw le;
}
}
Example 20
Project: jackrabbit-master File: DefaultLoginModule.java View source code |
/** * Handles the impersonation of given Credentials. * <p> * Current implementation takes {@link User} for the given Principal and * delegates the check to * {@link org.apache.jackrabbit.api.security.user.Impersonation#allows(javax.security.auth.Subject)} * * @param principal Principal to impersonate. * @param credentials Credentials used to create the impersonation subject. * @return false, if there is no User to impersonate, * true if impersonation is allowed * @throws javax.jcr.RepositoryException * @throws javax.security.auth.login.FailedLoginException * if credentials don't allow to impersonate to principal * @see AbstractLoginModule#impersonate(Principal, Credentials) */ @Override protected boolean impersonate(Principal principal, Credentials credentials) throws RepositoryException, FailedLoginException { if (user != null) { Subject impersSubject = getImpersonatorSubject(credentials); if (user.getImpersonation().allows(impersSubject)) { return true; } else { throw new FailedLoginException("attempt to impersonate denied for " + principal.getName()); } } else { log.debug("Failed to retrieve user to impersonate for principal name " + principal.getName()); return false; } }
Example 21
Project: jasig-cas-examples-robertoschwald-master File: WebserviceAuthenticationHandler.java View source code |
/**
* Authenticate user using webserviceClient.
* Throws a TesteeAuthenticationException if the useraccount is disabled.
*
*
* @param credential The provided credentials (e.g. username / pw)
* @return true if sucessfully authenticated, otherwise false.
* @throws GeneralSecurityException, PreventedException
* @see org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler#authenticateUsernamePasswordInternal(UsernamePasswordCredential)
*/
@Override
protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException {
final String username = credential.getUsername();
log.debug("Authenticating " + username);
Principal principal = this._webserviceClient.doAuthentication(credential);
if (principal != null) {
updatePersonAttributes(principal);
// Add Authorization checks if needed
return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
}
log.warn("Person received is null!");
throw new FailedLoginException();
}
Example 22
Project: karaf-master File: PropertiesLoginModuleTest.java View source code |
@Test
public void testLoginIncorrectPassword() throws Exception {
File f = File.createTempFile(getClass().getName(), ".tmp");
try {
Properties p = new Properties(f);
PropertiesBackingEngine pbe = new PropertiesBackingEngine(p);
pbe.addUser("abc", "xyz");
pbe.addUser("pqr", "abc");
PropertiesLoginModule module = new PropertiesLoginModule();
Map<String, String> options = new HashMap<String, String>();
options.put(PropertiesLoginModule.USER_FILE, f.getAbsolutePath());
CallbackHandler cb = new CallbackHandler() {
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback cb : callbacks) {
if (cb instanceof NameCallback) {
((NameCallback) cb).setName("abc");
} else if (cb instanceof PasswordCallback) {
((PasswordCallback) cb).setPassword("abc".toCharArray());
}
}
}
};
module.initialize(new Subject(), cb, null, options);
try {
module.login();
Assert.fail("The login should have failed as the passwords didn't match");
} catch (FailedLoginException fle) {
}
} finally {
if (!f.delete()) {
Assert.fail("Could not delete temporary file: " + f);
}
}
}
Example 23
Project: osm-sweden-master File: WikiBot.java View source code |
@Override
public synchronized void login(String username, char[] password) throws IOException, FailedLoginException {
super.login(username, password);
usernameLoggedInToWiki = username;
botHomePageTitle = "User:" + usernameLoggedInToWiki + "/bots/" + getBotName();
botLogPageTitle = botHomePageTitle + "/log";
try {
initializeBotPages();
} catch (LoginException e) {
throw new RuntimeException("Could not initialize Wiki pages to be associated with bot", e);
}
}
Example 24
Project: rt.equinox.bundles-master File: SecureStorageLoginModule.java View source code |
public boolean login() throws LoginException { NameCallback nameCallback = new NameCallback("username: "); PasswordCallback passwordCallback = new PasswordCallback("password: ", false); try { callbackHandler.handle(new Callback[] { nameCallback, passwordCallback }); } catch (IOException e) { throw new FailedLoginException("Cannot get username and password"); } catch (UnsupportedCallbackException e) { throw new FailedLoginException("Cannot get username and password"); } String username = nameCallback.getName(); char[] password = passwordCallback.getPassword(); userPrincipal = getUserInfo(username); try { isSuccess = userPrincipal.authenticate(DigestUtil.encrypt(new String(password)).toCharArray()); } catch (Exception e) { throw new FailedLoginException("Wrong credentials"); } if (isSuccess == true) { return isSuccess; } else { throw new FailedLoginException("Wrong credentials"); } }
Example 25
Project: certificate-master File: DriverKeyStoreLoader.java View source code |
public KeyStore getKeyStoreFromDriver(String driverName, String driverPath) {
Configuration.getInstance().addDriver(driverName, driverPath);
String pkcs11ConfigSettings = null;
KeyStore keyStore = null;
pkcs11ConfigSettings = (new Formatter()).format(PKCS11_CONTENT_CONFIG_FILE, driverName, driverPath).toString();
byte[] pkcs11ConfigBytes = pkcs11ConfigSettings.getBytes();
ByteArrayInputStream confStream = new ByteArrayInputStream(pkcs11ConfigBytes);
try {
Constructor<?> construtor = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(new Class[] { InputStream.class });
Provider pkcs11Provider = (Provider) construtor.newInstance(new Object[] { confStream });
Security.addProvider(pkcs11Provider);
confStream.close();
Method login = Class.forName("sun.security.pkcs11.SunPKCS11").getMethod("login", new Class[] { Subject.class, CallbackHandler.class });
login.invoke(Security.getProvider(pkcs11Provider.getName()), new Object[] { null, this.callback });
keyStore = KeyStore.getInstance(PKCS11_KEYSTORE_TYPE, pkcs11Provider.getName());
keyStore.load(null, null);
} catch (Exception e) {
if (e.getCause().toString().equals("javax.security.auth.login.FailedLoginException"))
throw new InvalidPinException(PINNUMBER_INVALID, e);
if (e.getCause().toString().equals("javax.security.auth.login.LoginException"))
throw new InvalidPinException(PINNUMBER_INVALID, e);
else
throw new PKCS11NotFoundException(DRIVER_LOAD_ERROR, e);
}
return keyStore;
}
Example 26
Project: com.idega.jackrabbit-master File: RepositoryLoginModule.java View source code |
@Override
protected boolean authenticate(Principal principal, Credentials credentials) throws FailedLoginException, RepositoryException {
String userId = getUserID(credentials);
if (StringUtil.isEmpty(userId)) {
return super.authenticate(principal, credentials);
}
if (userId.equals(getAdminId())) {
// Administrator user has all rights
return true;
}
if (credentials instanceof SimpleCredentials) {
credentials = new SimpleCredentials(userId, ((SimpleCredentials) credentials).getPassword());
}
return super.authenticate(principal, credentials);
}
Example 27
Project: cxf-master File: ServiceListJAASAuthenticator.java View source code |
public Subject doAuthenticate(final String username, final String password) {
try {
Subject subject = new Subject();
LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
((NameCallback) callbacks[i]).setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}
});
loginContext.login();
return subject;
} catch (FailedLoginException e) {
LOG.log(Level.FINE, "Login failed ", e);
return null;
} catch (AccountException e) {
LOG.log(Level.WARNING, "Account failure ", e);
return null;
} catch (GeneralSecurityException e) {
LOG.log(Level.SEVERE, "General Security Exception ", e);
return null;
}
}
Example 28
Project: gazpachoquest-master File: RespondentsLoginModule.java View source code |
@Override
public boolean login() throws LoginException {
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("username");
callbacks[1] = new PasswordCallback("password", true);
try {
handler.handle(callbacks);
String username = ((NameCallback) callbacks[0]).getName();
String password = String.valueOf(((PasswordCallback) callbacks[1]).getPassword());
logger.info("New username attempt for user: {}", username);
userPrincipal = doLogin(password);
logger.info("Access granted to user {}", userPrincipal.getFullName());
return true;
} catch (LoginException e) {
throw e;
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new FailedLoginException("An unknown error has occurred in authentication process");
}
}
Example 29
Project: gravia-master File: SecureHttpContext.java View source code |
private Subject doAuthenticate(final String username, final String password) {
try {
Subject subject = new Subject();
LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof NameCallback) {
((NameCallback) callbacks[i]).setName(username);
} else if (callbacks[i] instanceof PasswordCallback) {
((PasswordCallback) callbacks[i]).setPassword(password.toCharArray());
} else {
throw new UnsupportedCallbackException(callbacks[i]);
}
}
}
});
loginContext.login();
if (role != null && role.length() > 0) {
boolean found = false;
for (Principal p : subject.getPrincipals()) {
if (role.equals(p.getName()) || p instanceof Group && isGroupMember((Group) p, role)) {
found = true;
break;
}
}
if (!found) {
throw new FailedLoginException("User does not have the required role " + role);
}
}
return subject;
} catch (AccountException e) {
return null;
} catch (LoginException e) {
return null;
}
}
Example 30
Project: jdk7u-jdk-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @exception LoginException if the login operation fails * @exception SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11.Token.providerName.Password.")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 31
Project: jspwiki-master File: CookieAssertionLoginModule.java View source code |
/** * Logs in the user by calling back to the registered CallbackHandler with * an HttpRequestCallback. The CallbackHandler must supply the current * servlet HTTP request as its response. * @return the result of the login; if a cookie is * found, this method returns <code>true</code>. If not found, this * method throws a <code>FailedLoginException</code>. * @see javax.security.auth.spi.LoginModule#login() * @throws {@inheritDoc} */ public boolean login() throws LoginException { // Otherwise, let's go and look for the cookie! HttpRequestCallback hcb = new HttpRequestCallback(); Callback[] callbacks = new Callback[] { hcb }; try { m_handler.handle(callbacks); HttpServletRequest request = hcb.getRequest(); HttpSession session = (request == null) ? null : request.getSession(false); String sid = (session == null) ? NULL : session.getId(); String name = (request != null) ? getUserCookie(request) : null; if (name == null) { if (log.isDebugEnabled()) { log.debug("No cookie " + PREFS_COOKIE_NAME + " present in session ID=: " + sid); } throw new FailedLoginException("The user cookie was not found."); } if (log.isDebugEnabled()) { log.debug("Logged in session ID=" + sid + "; asserted=" + name); } // If login succeeds, commit these principals/roles m_principals.add(new WikiPrincipal(name, WikiPrincipal.FULL_NAME)); return true; } catch (IOException e) { log.error("IOException: " + e.getMessage()); return false; } catch (UnsupportedCallbackException e) { String message = "Unable to handle callback, disallowing login."; log.error(message, e); throw new LoginException(message); } }
Example 32
Project: ldaptive-master File: FreeIPAAccountState.java View source code |
@Override public void throwSecurityException() throws LoginException { switch(this) { case ACCOUNT_NOT_FOUND: throw new AccountNotFoundException(name()); case FAILED_AUTHENTICATION: throw new FailedLoginException(name()); case ACCOUNT_DISABLED: throw new FailedLoginException(name()); case PASSWORD_EXPIRED: throw new CredentialExpiredException(name()); case CREDENTIAL_NOT_FOUND: throw new FailedLoginException(name()); case ACCOUNT_EXPIRED: throw new AccountExpiredException(name()); case MAXIMUM_LOGINS_EXCEEDED: throw new AccountLockedException(name()); case LOGIN_TIME_LIMITED: throw new AccountLockedException(name()); case LOGIN_LOCKOUT: throw new AccountLockedException(name()); case UNKNOWN: throw new FailedLoginException(name()); default: throw new IllegalStateException("Unknown FreeIPA error: " + this); } }
Example 33
Project: Magnolia-master File: MagnoliaAuthenticationModule.java View source code |
protected void matchPassword() throws LoginException { String serverPassword = user.getPassword(); if (StringUtils.isEmpty(serverPassword)) { throw new FailedLoginException("we do not allow users with no password"); } if (!StringUtils.equals(serverPassword, new String(this.pswd))) { throw new FailedLoginException("passwords do not match"); } }
Example 34
Project: ManagedRuntimeInitiative-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @exception LoginException if the login operation fails * @exception SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11 Token [providerName] Password: ")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 35
Project: mina-sshd-master File: AbstractPEMResourceKeyPairParser.java View source code |
@Override
public Collection<KeyPair> extractKeyPairs(String resourceKey, String beginMarker, String endMarker, FilePasswordProvider passwordProvider, List<String> lines) throws IOException, GeneralSecurityException {
if (GenericUtils.isEmpty(lines)) {
return Collections.emptyList();
}
Boolean encrypted = null;
byte[] initVector = null;
String algInfo = null;
int dataStartIndex = -1;
for (int index = 0; index < lines.size(); index++) {
String line = GenericUtils.trimToEmpty(lines.get(index));
if (GenericUtils.isEmpty(line)) {
continue;
}
// check if header line - if not, assume data lines follow
int headerPos = line.indexOf(':');
if (headerPos < 0) {
dataStartIndex = index;
break;
}
if (line.startsWith("Proc-Type:")) {
if (encrypted != null) {
throw new StreamCorruptedException("Multiple encryption indicators in " + resourceKey);
}
line = line.substring(headerPos + 1).trim();
line = line.toUpperCase();
encrypted = Boolean.valueOf(line.contains("ENCRYPTED"));
} else if (line.startsWith("DEK-Info:")) {
if ((initVector != null) || (algInfo != null)) {
throw new StreamCorruptedException("Multiple encryption settings in " + resourceKey);
}
line = line.substring(headerPos + 1).trim();
headerPos = line.indexOf(',');
if (headerPos < 0) {
throw new StreamCorruptedException(resourceKey + ": Missing encryption data values separator in line '" + line + "'");
}
algInfo = line.substring(0, headerPos).trim();
String algInitVector = line.substring(headerPos + 1).trim();
initVector = BufferUtils.decodeHex(BufferUtils.EMPTY_HEX_SEPARATOR, algInitVector);
}
}
if (dataStartIndex < 0) {
throw new StreamCorruptedException("No data lines (only headers or empty) found in " + resourceKey);
}
List<String> dataLines = lines.subList(dataStartIndex, lines.size());
if ((encrypted != null) || (algInfo != null) || (initVector != null)) {
if (passwordProvider == null) {
throw new CredentialException("Missing password provider for encrypted resource=" + resourceKey);
}
String password = passwordProvider.getPassword(resourceKey);
if (GenericUtils.isEmpty(password)) {
throw new FailedLoginException("No password data for encrypted resource=" + resourceKey);
}
PrivateKeyEncryptionContext encContext = new PrivateKeyEncryptionContext(algInfo);
encContext.setPassword(password);
encContext.setInitVector(initVector);
byte[] encryptedData = KeyPairResourceParser.extractDataBytes(dataLines);
byte[] decodedData = applyPrivateKeyCipher(encryptedData, encContext, false);
try (InputStream bais = new ByteArrayInputStream(decodedData)) {
return extractKeyPairs(resourceKey, beginMarker, endMarker, passwordProvider, bais);
}
}
return super.extractKeyPairs(resourceKey, beginMarker, endMarker, passwordProvider, dataLines);
}
Example 36
Project: openjdk-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @throws IllegalStateException if the provider requires configuration * and Provider.configure has not been called * @throws LoginException if the login operation fails * @throws SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { if (!isConfigured()) { throw new IllegalStateException("Configuration is required"); } // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11.Token.providerName.Password.")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 37
Project: openjdk8-jdk-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @exception LoginException if the login operation fails * @exception SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11.Token.providerName.Password.")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 38
Project: ranger-master File: PamLoginModule.java View source code |
private boolean performLogin() throws LoginException {
try {
UnixUser user = _pam.authenticate(_username, _password);
_principal = new PamPrincipal(user);
_authSucceeded = true;
return true;
} catch (PAMException ex) {
LoginException le = new FailedLoginException("Invalid username or password");
le.initCause(ex);
throw le;
}
}
Example 39
Project: red5-plugins-master File: SimpleLoginModule.java View source code |
/** {@inheritDoc} */
public boolean login() throws LoginException {
// prompt for a user name and password
if (callbackHandler == null) {
throw new LoginException("Error: no CallbackHandler available, required to hold authentication information from the user");
}
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("User name: ");
callbacks[1] = new PasswordCallback("Password: ", false);
String userName;
char[] passwd;
try {
callbackHandler.handle(callbacks);
userName = ((NameCallback) callbacks[0]).getName();
char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
if (tmpPassword == null) {
// treat a NULL password as an empty password
tmpPassword = new char[0];
}
passwd = new char[tmpPassword.length];
System.arraycopy(tmpPassword, 0, passwd, 0, tmpPassword.length);
((PasswordCallback) callbacks[1]).clearPassword();
} catch (IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException("Error: " + uce.getCallback().toString() + " not available to hold authentication information");
}
String password = new String(passwd);
log.debug("User name: {} password: {}", userName, password);
// verify the username/password
SimplePrincipal prince = new SimplePrincipal(userName, password);
// look for a matching user
SimplePrincipal tmp = principals.get(userName);
// checks user name match
if (tmp != null && tmp.equals(prince)) {
// check passwords
if (tmp.getPassword().equals(prince.getPassword())) {
userPrincipal.set(prince);
log.debug("Authentication succeeded");
succeeded = true;
return true;
}
}
succeeded = false;
throw new FailedLoginException("Authentication failed");
}
Example 40
Project: rhq-master File: JDBCPrincipalCheckLoginModule.java View source code |
/** * @see org.jboss.security.auth.spi.UsernamePasswordLoginModule#getUsersPassword() */ @Override protected String getUsersPassword() throws LoginException { String username = getUsername(); if ("admin".equals(username)) { throw new FailedLoginException("Cannot log in as overlord"); } // what did the user enter? String password = getUsernameAndPassword()[1]; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dsJndiName); conn = ds.getConnection(); ps = conn.prepareStatement(principalsQuery); ps.setString(1, username); rs = ps.executeQuery(); if (rs.next() == true) { throw new FailedLoginException("username found in principals - do not continue"); } // return back the string entered by the user as a hash password = CryptoUtil.createPasswordHash("MD5", "base64", null, null, password); } catch (NamingException ex) { throw new LoginException(ex.toString(true)); } catch (SQLException ex) { throw new LoginException(ex.toString()); } finally { if (rs != null) { try { rs.close(); } catch (Exception e) { } } if (ps != null) { try { ps.close(); } catch (Exception e) { } } if (conn != null) { try { conn.close(); } catch (Exception ex) { } } } return password; }
Example 41
Project: Scute-master File: JAASLoginService.java View source code |
/**
* @inheritDoc
*
*/
@Override
public boolean authenticate(String name, char[] password, String server) throws Exception {
// If user has selected a different server, update the login service
if (server != null) {
if (!server.equals(getServer())) {
setServer(server);
}
}
// Clear the login context before attempting authentication
loginContext = null;
// authenticate the user.
try {
loginContext = new LoginContext(getServer(), new JAASCallbackHandler(name, password));
loginContext.login();
return true;
} catch (AccountExpiredException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (CredentialExpiredException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (FailedLoginException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (LoginException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (Throwable e) {
LOG.log(Level.WARNING, "", e);
return false;
}
}
Example 42
Project: SikuliX-2014-master File: JAASLoginService.java View source code |
/**
* @inheritDoc
*
*/
@Override
public boolean authenticate(String name, char[] password, String server) throws Exception {
// If user has selected a different server, update the login service
if (server != null) {
if (!server.equals(getServer())) {
setServer(server);
}
}
// Clear the login context before attempting authentication
loginContext = null;
// authenticate the user.
try {
loginContext = new LoginContext(getServer(), new JAASCallbackHandler(name, password));
loginContext.login();
return true;
} catch (AccountExpiredException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (CredentialExpiredException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (FailedLoginException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (LoginException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (Throwable e) {
LOG.log(Level.WARNING, "", e);
return false;
}
}
Example 43
Project: solmix-master File: AuthenticationModule.java View source code |
/** * @throws LoginException * @throws SlxException * */ @Override public void validateUser() throws LoginException, SlxException { user = userManager.getUser(name); if (this.getMaxAttempts() > 0 && !UserManager.ANONYMOUS_USER.equals(user.getName()) && getTimeLock() > 0) { Calendar currentTime = new GregorianCalendar(TimeZone.getDefault()); Calendar lockTime = new GregorianCalendar(TimeZone.getDefault()); if (user.getReleaseTime() != 0) { lockTime.clear(); lockTime.setTime(new Date(user.getReleaseTime())); if (lockTime.after(currentTime)) { throw new LoginException("User account " + this.name + " is locked until " + new Date(user.getReleaseTime()) + "."); } } } String serverPassword = user.getPassword(); if (this.user == null) { throw new AccountNotFoundException("User account " + this.name + " not found."); } if (!this.user.isEnabled()) { throw new AccountLockedException("User account " + this.name + " is locked."); } if (serverPassword == null || serverPassword.isEmpty()) { throw new FailedLoginException("Does not allow login to users with no password."); } String encrypedPsd = getEncryptedPassword(new String(this.pswd)); boolean match = checkPassword(serverPassword, encrypedPsd); if (!match) { if (this.getMaxAttempts() > 0 && !UserManager.ANONYMOUS_USER.equals(user.getName())) { userManager.setProperty(user, User.RPOP_FAILED_LOGIN_ATTEMPTS, user.getFailedLoginAttempts() + 1); // hard lock if (user.getFailedLoginAttempts() > this.getMaxAttempts() && this.getTimeLock() <= 0) { userManager.setProperty(user, User.PROP_ENABLE, Boolean.FALSE); userManager.setProperty(user, User.RPOP_FAILED_LOGIN_ATTEMPTS, new Integer(0)); } else // time period lock. if (user.getFailedLoginAttempts() > this.getMaxAttempts() && this.getTimeLock() > 0) { userManager.setProperty(user, User.RPOP_FAILED_LOGIN_ATTEMPTS, new Integer(0)); Calendar calendar = new GregorianCalendar(TimeZone.getDefault()); calendar.add(Calendar.MINUTE, (int) getTimeLock()); userManager.setProperty(user, User.RPOP_RELEASE_TIME, new Long(calendar.getTime().getTime())); } } throw new FailedLoginException("Passwords do not match"); } }
Example 44
Project: swingx-master File: JAASLoginService.java View source code |
/**
* @inheritDoc
*
*/
@Override
public boolean authenticate(String name, char[] password, String server) throws Exception {
// If user has selected a different server, update the login service
if (server != null) {
if (!server.equals(getServer())) {
setServer(server);
}
}
// Clear the login context before attempting authentication
loginContext = null;
// authenticate the user.
try {
loginContext = new LoginContext(getServer(), new JAASCallbackHandler(name, password));
loginContext.login();
return true;
} catch (AccountExpiredException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (CredentialExpiredException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (FailedLoginException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (LoginException e) {
LOG.log(Level.WARNING, "", e);
return false;
} catch (Throwable e) {
LOG.log(Level.WARNING, "", e);
return false;
}
}
Example 45
Project: Virgo-kernel-sandbox-master File: KernelLoginModule.java View source code |
public boolean login() throws LoginException { // We do not actually care about these prompts but they must be populated NameCallback nameCallback = new NameCallback("username"); PasswordCallback passwordCallback = new PasswordCallback("password", false); try { this.callbackHandler.handle(new Callback[] { nameCallback, passwordCallback }); } catch (UnsupportedCallbackException e) { throw new FailedLoginException("Unable to get username and password"); } catch (IOException e) { throw new FailedLoginException("Unable to get username and password"); } this.user = this.credentialStore.getUser(nameCallback.getName()); this.authenticationResult = this.user.authenticate(new String(passwordCallback.getPassword())); if (authenticationResult) { return true; } throw new FailedLoginException("Credentials did not match"); }
Example 46
Project: wildfly-camel-master File: SecuredRouteTestCase.java View source code |
@Test
public void testInvalidCredentials() throws Exception {
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").policy(new DomainAuthorizationPolicy()).transform(body().prepend("Hello "));
}
});
camelctx.start();
try {
ProducerTemplate producer = camelctx.createProducerTemplate();
try {
Subject subject = getAuthenticationToken("user-domain", AnnotatedSLSB.USERNAME, "bogus");
producer.requestBodyAndHeader("direct:start", "Kermit", Exchange.AUTHENTICATION, subject, String.class);
Assert.fail("CamelExecutionException expected");
} catch (CamelExecutionException ex) {
Throwable cause = ex.getCause();
Assert.assertEquals(FailedLoginException.class, cause.getClass());
Assert.assertTrue(cause.getMessage(), cause.getMessage().contains("Password invalid/Password required"));
}
} finally {
camelctx.stop();
}
}
Example 47
Project: josso1-master File: SSOGatewayLoginModuleNoCustomPrincipalsImpl.java View source code |
/** * Authenticate the user by prompting for the SSO Session Identifier assigned by the SSO Gateway on logon. * * This method obtains from the gateway, using the provided session identifier, the user associated with * such session identifier. * Only the NameCallBack is used, since its not a user/password pair but only one value containing the session * identifier. Any other callback type is ignored. * * @return true in all cases since this LoginModule * should not be ignored. * * @exception FailedLoginException if the authentication fails. * * @exception LoginException if this LoginModule * is unable to perform the authentication. */ public boolean login() throws LoginException { if (_callbackHandler == null) throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); Callback[] callbacks = new Callback[2]; // Just ask for the session identifier callbacks[0] = new NameCallback("ssoSessionId"); callbacks[1] = new PasswordCallback("password", false); String ssoSessionId; String ssoSessionId2 = null; try { _callbackHandler.handle(callbacks); ssoSessionId = ((NameCallback) callbacks[0]).getName(); if (((PasswordCallback) callbacks[1]).getPassword() != null) ssoSessionId2 = String.valueOf(((PasswordCallback) callbacks[1]).getPassword()); _requester = ""; // Check for nulls ? SSOAgentRequest request = AbstractSSOAgent._currentRequest.get(); if (request != null) _requester = request.getRequester(); else logger.warn("No SSO Agent request found in thread local variable, can't identify requester"); } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user"); } logger.debug("Requested authentication to gateway by " + _requester + " using sso session " + ssoSessionId + "/" + ssoSessionId2); try { if (ssoSessionId2 != null && !ssoSessionId2.equals(ssoSessionId)) ssoSessionId = ssoSessionId2; // If no session is found, ignore this module. if (ssoSessionId == null) { if (logger.isDebugEnabled()) logger.debug("Session authentication failed : " + ssoSessionId); _succeeded = false; return false; } _currentSSOSessionId = ssoSessionId; SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager(); SSOUser jossoUser = im.findUserInSession(_requester, ssoSessionId); WLSUser wlsUser = new WLSUserImpl(jossoUser.getName()); if (logger.isDebugEnabled()) logger.debug("Session authentication succeeded : " + ssoSessionId); _ssoUserPrincipal = wlsUser; _succeeded = true; } catch (SSOIdentityException e) { logger.debug(e.getMessage()); _succeeded = false; return false; } catch (Exception e) { logger.error("Session login failed for Principal : " + _ssoUserPrincipal + e.getMessage()); if (logger.isDebugEnabled()) logger.debug(e.getMessage(), e); _succeeded = false; clearCredentials(); throw new FailedLoginException("Fatal error authenticating session : " + _ssoUserPrincipal + " : " + e.getMessage()); } return true; }
Example 48
Project: atricore-idbus-master File: JaasSecurityProvider.java View source code |
public Subject doAuthenticate(final String username, final String password) { try { Subject subject = new Subject(); LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() { public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { for (int i = 0; i < callbacks.length; i++) { if (callbacks[i] instanceof NameCallback) { ((NameCallback) callbacks[i]).setName(username); } else if (callbacks[i] instanceof PasswordCallback) { ((PasswordCallback) callbacks[i]).setPassword(password.toCharArray()); } else { throw new UnsupportedCallbackException(callbacks[i]); } } } }); loginContext.login(); if (role != null && role.length() > 0) { String clazz = "org.apache.karaf.jaas.modules.RolePrincipal"; String name = role; int idx = role.indexOf(':'); if (idx > 0) { clazz = role.substring(0, idx); name = role.substring(idx + 1); } boolean found = false; for (Principal p : subject.getPrincipals()) { if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) { found = true; break; } } if (!found) { throw new FailedLoginException("User does not have the required role " + role); } } return subject; } catch (FailedLoginException e) { LOG.debug("Login failed", e); return null; } catch (AccountException e) { LOG.warn("Account failure", e); return null; } catch (GeneralSecurityException e) { LOG.error("General Security Exception", e); return null; } }
Example 49
Project: cassa-master File: CassandraLoginModule.java View source code |
/** * Authenticate the user, obtaining credentials from the CallbackHandler * supplied in {@code}initialize{@code}. As long as the configured * {@code}IAuthenticator{@code} supports the optional * {@code}legacyAuthenticate{@code} method, it can be used here. * * @return true in all cases since this {@code}LoginModule{@code} * should not be ignored. * @exception FailedLoginException if the authentication fails. * @exception LoginException if this {@code}LoginModule{@code} is unable to * perform the authentication. */ @Override public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) { logger.info("No CallbackHandler available for authentication"); throw new LoginException("Authentication failed"); } NameCallback nc = new NameCallback("username: "); PasswordCallback pc = new PasswordCallback("password: ", false); try { callbackHandler.handle(new Callback[] { nc, pc }); username = nc.getName(); char[] tmpPassword = pc.getPassword(); if (tmpPassword == null) tmpPassword = new char[0]; password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); pc.clearPassword(); } catch (IOExceptionUnsupportedCallbackException | e) { logger.info("Unexpected exception processing authentication callbacks", e); throw new LoginException("Authentication failed"); } // verify the credentials try { authenticate(); } catch (AuthenticationException e) { succeeded = false; cleanUpInternalState(); throw new FailedLoginException(e.getMessage()); } succeeded = true; return true; }
Example 50
Project: cassandra-master File: CassandraLoginModule.java View source code |
/** * Authenticate the user, obtaining credentials from the CallbackHandler * supplied in {@code}initialize{@code}. As long as the configured * {@code}IAuthenticator{@code} supports the optional * {@code}legacyAuthenticate{@code} method, it can be used here. * * @return true in all cases since this {@code}LoginModule{@code} * should not be ignored. * @exception FailedLoginException if the authentication fails. * @exception LoginException if this {@code}LoginModule{@code} is unable to * perform the authentication. */ @Override public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) { logger.info("No CallbackHandler available for authentication"); throw new LoginException("Authentication failed"); } NameCallback nc = new NameCallback("username: "); PasswordCallback pc = new PasswordCallback("password: ", false); try { callbackHandler.handle(new Callback[] { nc, pc }); username = nc.getName(); char[] tmpPassword = pc.getPassword(); if (tmpPassword == null) tmpPassword = new char[0]; password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); pc.clearPassword(); } catch (IOExceptionUnsupportedCallbackException | e) { logger.info("Unexpected exception processing authentication callbacks", e); throw new LoginException("Authentication failed"); } // verify the credentials try { authenticate(); } catch (AuthenticationException e) { succeeded = false; cleanUpInternalState(); throw new FailedLoginException(e.getMessage()); } succeeded = true; return true; }
Example 51
Project: chililog-server-master File: JAASLoginModule.java View source code |
/** * <p> * We check the credentials against the repository. By convention, the username is the repository name and the * password is either the publisher or subscriber password. The role assigned to the user is constructed from the * combination of username and publisher password. * </p> * * @return Returns true if this method succeeded, or false if this LoginModule should be ignored. */ public boolean login() throws LoginException { try { // // This code is from org.hornetq.spi.core.security.JAASSecurityManager.getAuthenticatedSubject(); // It is how HornetQ uses JAAS to authenticate // // Subject subject = new Subject(); // if (user != null) // { // subject.getPrincipals().add(principal); // } // subject.getPrivateCredentials().add(passwordChars); // LoginContext lc = new LoginContext(configurationName, subject, callbackHandler, config); // Get the user name Iterator<Principal> iterator = _subject.getPrincipals().iterator(); String username = iterator.next().getName(); if (StringUtils.isBlank(username)) { throw new FailedLoginException("Username is requried."); } // Get the password Iterator<char[]> iterator2 = _subject.getPrivateCredentials(char[].class).iterator(); char[] passwordChars = iterator2.next(); String password = new String(passwordChars); if (StringUtils.isBlank(password)) { throw new FailedLoginException("Password is requried."); } // Check if system user if (username.equals(_systemUsername) && password.equals(_systemPassword)) { Group roles = new SimpleGroup("Roles"); roles.addMember(new SimplePrincipal(UserBO.SYSTEM_ADMINISTRATOR_ROLE_NAME)); _subject.getPrincipals().add(roles); return true; } // Let's validate non-system user DB db = MongoConnection.getInstance().getConnection(); UserBO user = UserController.getInstance().tryGetByUsername(db, username); if (user == null) { throw new FailedLoginException("Invalid username or password."); } if (StringUtils.isBlank(password) || !user.validatePassword(password)) { throw new FailedLoginException("Invalid username or password."); } // Add role Group roles = new SimpleGroup("Roles"); for (String role : user.getRoles()) { roles.addMember(new SimplePrincipal(role)); } _subject.getPrincipals().add(roles); // OK return true; } catch (Exception ex) { throw new LoginException(ex.getMessage()); } }
Example 52
Project: com.activecq.samples-master File: SampleLoginModule.java View source code |
/**
* Handles the impersonation of the Principal using the provided
* Credentials.
* <p/>
* Impersonation only occurs if the provided Credentials allow for the
* impersonation of the Principal.
*
* @param principalToImpersonate Principal to impersonate
* @param impersonatorCredentials Credentials used to create the
* impersonation subject.
* @return
* @throws RepositoryException
* @throws LoginException
*/
@Override
protected boolean impersonate(Principal principalToImpersonate, Credentials impersonatorCredentials) throws RepositoryException, LoginException {
Authorizable authorizableToImpersonate = userManager.getAuthorizable(principalToImpersonate);
if (authorizableToImpersonate == null || authorizableToImpersonate.isGroup()) {
return false;
}
Subject impersonatorSubject = getImpersonatorSubject(impersonatorCredentials);
User userToImpersonate = (User) authorizableToImpersonate;
if (userToImpersonate.getImpersonation().allows(impersonatorSubject)) {
return true;
} else {
throw new FailedLoginException("attempt to impersonate denied for " + principalToImpersonate.getName());
}
}
Example 53
Project: exist-master File: EXistDBLoginModule.java View source code |
/** * Authenticate the user by prompting for a user name and password. * * <p> * * @return true in all cases since this <code>LoginModule</code> should not * be ignored. * * @exception FailedLoginException * if the authentication fails. * <p> * * @exception LoginException * if this <code>LoginModule</code> is unable to perform the * authentication. */ public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); } final Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("user name: "); callbacks[1] = new PasswordCallback("password: ", false); // username and password String username; char[] password; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) { // treat a NULL password as an empty password tmpPassword = new char[0]; } password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); ((PasswordCallback) callbacks[1]).clearPassword(); } catch (final java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (final UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information" + " from the user"); } // print debugging information if (debug) { System.out.println("\t\t[eXistLoginModule] user entered user name: " + username); } try { userPrincipal = BrokerPool.getInstance().getSecurityManager().authenticate(username, password); } catch (final AuthenticationException e) { if (debug) { System.out.println("\t\t[eXistLoginModule] authentication failed"); } throw new FailedLoginException(e.getMessage()); } catch (final EXistException e) { throw new FailedLoginException(e.getMessage()); } succeeded = userPrincipal.isAuthenticated(); return true; }
Example 54
Project: jetty.project-master File: AbstractLoginModule.java View source code |
/** * @see javax.security.auth.spi.LoginModule#login() * @return true if is authenticated, false otherwise * @throws LoginException if unable to login */ public boolean login() throws LoginException { try { if (isIgnored()) return false; if (callbackHandler == null) throw new LoginException("No callback handler"); Callback[] callbacks = configureCallbacks(); callbackHandler.handle(callbacks); String webUserName = ((NameCallback) callbacks[0]).getName(); Object webCredential = null; //first check if ObjectCallback has the credential webCredential = ((ObjectCallback) callbacks[1]).getObject(); if (webCredential == null) //use standard PasswordCallback webCredential = ((PasswordCallback) callbacks[2]).getPassword(); if ((webUserName == null) || (webCredential == null)) { setAuthenticated(false); throw new FailedLoginException(); } UserInfo userInfo = getUserInfo(webUserName); if (userInfo == null) { setAuthenticated(false); throw new FailedLoginException(); } currentUser = new JAASUserInfo(userInfo); setAuthenticated(currentUser.checkCredential(webCredential)); if (isAuthenticated()) { currentUser.fetchRoles(); return true; } else throw new FailedLoginException(); } catch (IOException e) { throw new LoginException(e.toString()); } catch (UnsupportedCallbackException e) { throw new LoginException(e.toString()); } catch (Exception e) { if (e instanceof LoginException) throw (LoginException) e; throw new LoginException(e.toString()); } }
Example 55
Project: knowledge_vault-master File: OKMLoginModule.java View source code |
@Override
public boolean login() throws LoginException {
log.debug("login()");
boolean ok;
// prompt for a user name and password
if (callbackHandler == null) {
throw new LoginException("no CallbackHandler available");
}
if (users == null)
throw new LoginException("Missing users.properties file.");
if (roles == null)
throw new LoginException("Missing roles.properties file.");
boolean authenticated = false;
principals.clear();
try {
// Get credentials using a JAAS callback
CredentialsCallback ccb = new CredentialsCallback();
callbackHandler.handle(new Callback[] { ccb });
Credentials creds = ccb.getCredentials();
// Use the credentials to set up principals
if (creds != null) {
if (creds instanceof SimpleCredentials) {
SimpleCredentials sc = (SimpleCredentials) creds;
// authenticate
Object attr = sc.getAttribute(SecurityConstants.IMPERSONATOR_ATTRIBUTE);
if (attr != null && attr instanceof Subject) {
Subject impersonator = (Subject) attr;
// @todo check privileges to 'impersonate' the user represented by the supplied credentials
log.debug("***** RARO ******");
log.debug(impersonator.toString());
log.debug("***** RARO ******");
} else {
// @todo implement simple username/password authentication
log.debug("***********");
log.debug(sc.getUserID() + " -> " + new String(sc.getPassword()));
log.debug("***********");
if (users.getProperty(sc.getUserID()).equals(new String(sc.getPassword()))) {
log.debug("*********** BIEN");
authenticated = true;
} else {
log.debug("*********** MAL");
authenticated = false;
}
}
if ("anonymousUserId".equals(sc.getUserID())) {
principals.add(new AnonymousPrincipal());
authenticated = true;
} else {
// else assume the user we authenticated is the UserPrincipal
principals.add(new UserPrincipal(sc.getUserID()));
//java.security.acl.;
authenticated = true;
}
}
} else if (defaultUserId != null) {
//principals.add(new UserPrincipal(defaultUserId));
principals.add(new SystemPrincipal());
authenticated = true;
} else {
principals.add(new AnonymousPrincipal());
authenticated = true;
}
} catch (java.io.IOException ioe) {
throw new LoginException(ioe.toString());
} catch (UnsupportedCallbackException uce) {
throw new LoginException(uce.getCallback().toString() + " not available");
}
if (authenticated) {
ok = !principals.isEmpty();
} else {
// authentication failed: clean out state
principals.clear();
throw new FailedLoginException();
}
log.debug("login: " + ok);
return ok;
}
Example 56
Project: kylo-master File: KyloRestLoginModule.java View source code |
@Override protected boolean doLogin() throws Exception { // Get username and password final NameCallback nameCallback = new NameCallback("Username: "); final PasswordCallback passwordCallback = new PasswordCallback("Password: ", false); final String username; final String password; if (loginUser == null) { // Use user's own username and password to access the REST API if a loginUser was not provided. handle(nameCallback, passwordCallback); username = nameCallback.getName(); password = new String(passwordCallback.getPassword()); } else { // Using the loginUser to access API so only need the authenticating user's name. handle(nameCallback); username = loginUser; password = loginPassword; } final LoginJerseyClientConfig userConfig = new LoginJerseyClientConfig(config); userConfig.setUsername(username); userConfig.setPassword(password); final UserPrincipal user; try { user = retrieveUser(nameCallback.getName(), userConfig); } catch (final NotAuthorizedException e) { log.debug("Received unauthorized response from Login API for user: {}", username); throw new CredentialException("The username and password combination do not match."); } catch (final ProcessingException e) { log.error("Failed to process response from Login API for user: {}", username, e); throw new FailedLoginException("The login service is unavailable."); } catch (final WebApplicationException e) { log.error("Received unexpected response from Login API for user: {}", username, e); throw new FailedLoginException("The login service is unavailable."); } // Parse response if (user == null) { log.debug("Received null response from Login API for user: {}", username); throw new AccountNotFoundException("No account exists with the name: " + username); } else if (!user.isEnabled()) { log.debug("User from Login API is disabled: {}", username); throw new AccountLockedException("The account \"" + username + "\" is currently disabled"); } addNewUserPrincipal(user.getSystemName()); user.getGroups().forEach(this::addNewGroupPrincipal); return true; }
Example 57
Project: lutece-core-master File: AdminLoginJspBean.java View source code |
/**
* Process the login of user
*
* @param request
* The HTTP Request
* @return The Jsp URL of the process result
* @throws Exception
* The exception
*/
public String doLogin(HttpServletRequest request) throws Exception {
if (request.getScheme().equals(CONSTANT_HTTP) && AppHTTPSService.isHTTPSSupportEnabled()) {
return JSP_URL_ADMIN_LOGIN;
}
// recovery of the login attributes
String strAccessCode = request.getParameter(Parameters.ACCESS_CODE);
String strPassword = request.getParameter(Parameters.PASSWORD);
if (strAccessCode == null || strPassword == null) {
// TIME RESISTANT ATTACK
// Computation time is equal to the time needed by a legitimate user
strAccessCode = "";
strPassword = "";
}
String strLoginUrl = AdminAuthenticationService.getInstance().getLoginPageUrl();
try {
AdminAuthenticationService.getInstance().loginUser(request, strAccessCode, strPassword);
} catch (FailedLoginException ex) {
UserLog userLog = new UserLog();
userLog.setAccessCode(strAccessCode);
userLog.setIpAddress(SecurityUtil.getRealIp(request));
userLog.setDateLogin(new java.sql.Timestamp(new java.util.Date().getTime()));
userLog.setLoginStatus(UserLog.LOGIN_DENIED);
UserLogHome.addUserLog(userLog);
return AdminMessageService.getMessageUrl(request, Messages.MESSAGE_AUTH_FAILURE, strLoginUrl, AdminMessage.TYPE_STOP);
} catch (LoginException ex) {
AppLogService.error("Error during connection for user access code :" + strAccessCode, ex);
return AdminMessageService.getMessageUrl(request, Messages.MESSAGE_AUTH_FAILURE, strLoginUrl, AdminMessage.TYPE_STOP);
}
UrlItem url;
AdminUser user = AdminUserHome.findUserByLogin(strAccessCode);
if (user.isPasswordReset()) {
String strRedirectUrl = AdminMessageService.getMessageUrl(request, Messages.MESSAGE_USER_MUST_CHANGE_PASSWORD, JSP_URL_MODIFY_DEFAULT_USER_PASSOWRD, AdminMessage.TYPE_ERROR);
url = new UrlItem(strRedirectUrl);
} else {
String strNextUrl = AdminAuthenticationService.getInstance().getLoginNextUrl(request);
if (StringUtils.isNotBlank(strNextUrl)) {
url = new UrlItem(strNextUrl);
} else {
url = AppPathService.resolveRedirectUrl(request, AppPathService.getAdminMenuUrl());
}
}
return url.getUrl();
}
Example 58
Project: resource-manager-master File: LDAPLoginModule.java View source code |
/** * Authenticate the user by getting the user name and password from the * CallbackHandler. * * <p> * * @return true in all cases since this <code>LDAPLoginModule</code> * should not be ignored. * * @exception FailedLoginException * if the authentication fails. * <p> * * @exception LoginException * if this <code>LDAPLoginModule</code> is unable to * perform the authentication. */ @Override public boolean login() throws LoginException { succeeded = false; if (callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); } try { Callback[] callbacks = new Callback[] { new NoCallback() }; // gets the user name, password, group Membership, and group Hierarchy from call back handler callbackHandler.handle(callbacks); Map<String, Object> params = ((NoCallback) callbacks[0]).get(); String username = (String) params.get("username"); String password = (String) params.get("pw"); params.clear(); ((NoCallback) callbacks[0]).clear(); if (username == null) { logger.info("No username has been specified for authentication"); throw new FailedLoginException("No username has been specified for authentication"); } succeeded = logUser(username, password); return succeeded; } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user"); } }
Example 59
Project: scheduling-master File: LDAPLoginModule.java View source code |
/** * Authenticate the user by getting the user name and password from the * CallbackHandler. * * <p> * * @return true in all cases since this <code>LDAPLoginModule</code> * should not be ignored. * * @exception FailedLoginException * if the authentication fails. * <p> * * @exception LoginException * if this <code>LDAPLoginModule</code> is unable to * perform the authentication. */ @Override public boolean login() throws LoginException { succeeded = false; if (callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); } try { Callback[] callbacks = new Callback[] { new NoCallback() }; // gets the user name, password, group Membership, and group Hierarchy from call back handler callbackHandler.handle(callbacks); Map<String, Object> params = ((NoCallback) callbacks[0]).get(); String username = (String) params.get("username"); String password = (String) params.get("pw"); params.clear(); ((NoCallback) callbacks[0]).clear(); if (username == null) { logger.info("No username has been specified for authentication"); throw new FailedLoginException("No username has been specified for authentication"); } succeeded = logUser(username, password); return succeeded; } catch (java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information " + "from the user"); } }
Example 60
Project: subetha-master File: AuthAction.java View source code |
/**
* Actually perform the login logic by calling into the JAAS stack.
*
* @throws LoginException if it didn't work.
*/
public void login(String who, String password) throws LoginException {
SubEthaLogin rl = Backend.instance().getLogin();
rl.logout(this.getCtx().getRequest());
log.log(Level.FINE, "Successful authentication for: {0}", who);
if (!rl.login(who, password, this.getCtx().getRequest()))
throw new FailedLoginException("Bad username or password");
}
Example 61
Project: tizzit-master File: Util.java View source code |
/** Execute the rolesQuery against the dsJndiName to obtain the roles for
the authenticated user.
@return Group[] containing the sets of roles
*/
static Group[] getRoleSets(String username, String dsJndiName, String rolesQuery, AbstractServerLoginModule aslm, boolean suspendResume) throws LoginException {
Logger log = aslm.log;
boolean trace = log.isTraceEnabled();
Connection conn = null;
HashMap setsMap = new HashMap();
PreparedStatement ps = null;
ResultSet rs = null;
Transaction tx = null;
if (suspendResume) {
tx = TransactionDemarcationSupport.suspendAnyTransaction();
if (trace)
log.trace("suspendAnyTransaction");
}
try {
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup(dsJndiName);
conn = ds.getConnection();
// Get the user role names
if (trace)
log.trace("Excuting query: " + rolesQuery + ", with username: " + username);
ps = conn.prepareStatement(rolesQuery);
try {
ps.setString(1, username);
} catch (ArrayIndexOutOfBoundsException ignore) {
}
rs = ps.executeQuery();
if (rs.next() == false) {
if (trace)
log.trace("No roles found");
if (aslm.getUnauthenticatedIdentity() == null)
throw new FailedLoginException("No matching username found in Roles");
/* We are running with an unauthenticatedIdentity so create an
empty Roles set and return.
*/
Group[] roleSets = { new SimpleGroup("Roles") };
return roleSets;
}
do {
String name = rs.getString(1);
String groupName = rs.getString(2);
if (groupName == null || groupName.length() == 0)
groupName = "Roles";
Group group = (Group) setsMap.get(groupName);
if (group == null) {
group = new SimpleGroup(groupName);
setsMap.put(groupName, group);
}
try {
Principal p = aslm.createIdentity(name);
if (trace)
log.trace("Assign user to role " + name);
group.addMember(p);
} catch (Exception e) {
if (log.isDebugEnabled())
log.debug("Failed to create principal: " + name, e);
}
} while (rs.next());
} catch (NamingException ex) {
LoginException le = new LoginException("Error looking up DataSource from: " + dsJndiName);
le.initCause(ex);
throw le;
} catch (SQLException ex) {
LoginException le = new LoginException("Query failed");
le.initCause(ex);
throw le;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception ex) {
}
}
if (suspendResume) {
TransactionDemarcationSupport.resumeAnyTransaction(tx);
if (trace)
log.trace("resumeAnyTransaction");
}
}
Group[] roleSets = new Group[setsMap.size()];
setsMap.values().toArray(roleSets);
return roleSets;
}
Example 62
Project: XSLT-master File: EXistDBLoginModule.java View source code |
/** * Authenticate the user by prompting for a user name and password. * * <p> * * @return true in all cases since this <code>LoginModule</code> should not * be ignored. * * @exception FailedLoginException * if the authentication fails. * <p> * * @exception LoginException * if this <code>LoginModule</code> is unable to perform the * authentication. */ public boolean login() throws LoginException { // prompt for a user name and password if (callbackHandler == null) { throw new LoginException("Error: no CallbackHandler available " + "to garner authentication information from the user"); } final Callback[] callbacks = new Callback[2]; callbacks[0] = new NameCallback("user name: "); callbacks[1] = new PasswordCallback("password: ", false); // username and password String username; char[] password; try { callbackHandler.handle(callbacks); username = ((NameCallback) callbacks[0]).getName(); char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword(); if (tmpPassword == null) { // treat a NULL password as an empty password tmpPassword = new char[0]; } password = new char[tmpPassword.length]; System.arraycopy(tmpPassword, 0, password, 0, tmpPassword.length); ((PasswordCallback) callbacks[1]).clearPassword(); } catch (final java.io.IOException ioe) { throw new LoginException(ioe.toString()); } catch (final UnsupportedCallbackException uce) { throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information" + " from the user"); } // print debugging information if (debug) { System.out.println("\t\t[eXistLoginModule] user entered user name: " + username); } try { userPrincipal = BrokerPool.getInstance().getSecurityManager().authenticate(username, password); } catch (final AuthenticationException e) { if (debug) { System.out.println("\t\t[eXistLoginModule] authentication failed"); } throw new FailedLoginException(e.getMessage()); } catch (final EXistException e) { throw new FailedLoginException(e.getMessage()); } succeeded = userPrincipal.isAuthenticated(); return true; }
Example 63
Project: jspresso-ce-master File: AbstractFrontendController.java View source code |
/**
* Perform JAAS login.
*
* @return the logged-in subject or null if login failed.
*/
protected Subject performJAASLogin() {
CallbackHandler lch = getLoginCallbackHandler();
try {
LoginContext lc;
try {
lc = new LoginContext(getLoginContextName(), lch);
} catch (LoginException le) {
LOG.error("Cannot create LoginContext.", le);
return null;
} catch (SecurityException se) {
LOG.error("Cannot create LoginContext.", se);
return null;
}
lc.login();
return lc.getSubject();
} catch (LoginException le) {
if (!(le instanceof FailedLoginException)) {
String message = le.getMessage();
if (message.indexOf(':') > 0) {
String exceptionClassName = message.substring(0, message.indexOf(':'));
try {
if (Throwable.class.isAssignableFrom(Class.forName(exceptionClassName))) {
LOG.error("A technical exception occurred on login module.", le);
}
} catch (ClassNotFoundException ignored) {
}
}
}
return null;
}
}
Example 64
Project: screensaver-master File: ScreensaverLoginModule.java View source code |
private boolean authenticateUser(String username, char[] password) throws LoginException { // verify the username/password try { _user = findUserByLoginId(username); if (_user != null) { log.info(FOUND_SCREENSAVER_USER + " '" + username + "'"); verifyLoginPrivilege(username); if (_user.getDigestedPassword().equals(CryptoUtils.digest(password))) { _isAuthenticated = true; _authenticationResult = new SimpleAuthenticationResult(username, new String(password), true, 1, "success", "user authenticated with native Screensaver account"); } else { _isAuthenticated = false; _authenticationResult = new SimpleAuthenticationResult(username, new String(password), _isAuthenticated, 0, "failure", "user authentication failed for native Screensaver account"); } } else { _user = findUserByECommonsId(username); if (_user != null) { log.info(FOUND_ECOMMONS_USER + " '" + _user.getECommonsId() + "'"); verifyLoginPrivilege(username); _authenticationResult = _authenticationClient.authenticate(new Credentials(_user.getECommonsId(), new String(password))); _isAuthenticated = _authenticationResult.isAuthenticated(); } else { String message = NO_SUCH_USER + " '" + username + "'"; log.info(message); throw new FailedLoginException(message); } } if (_isAuthenticated) { log.info("authentication succeeded for user '" + username + "' with status code " + _authenticationResult.getStatusCode() + " (" + _authenticationResult.getStatusCodeCategory() + ")"); return true; } else { // authentication failed, clean out state String statusMessage = _authenticationResult.getStatusMessage(); log.info("authentication failed for user '" + username + "' with status code " + _authenticationResult.getStatusCode() + " (" + _authenticationResult.getStatusCodeCategory() + ": '" + statusMessage + "')"); reset(true); throw new FailedLoginException(statusMessage); } } catch (AuthenticationRequestException e) { log.error("error during login with authentication server request: " + e.getMessage()); throw new LoginException(e.getMessage()); } catch (AuthenticationResponseException e) { log.error("error during login with authentication server response: " + e.getMessage()); throw new LoginException(e.getMessage()); } }
Example 65
Project: tomcat70-master File: JAASRealm.java View source code |
// -------------------------------------------------------- Package Methods
// ------------------------------------------------------ Protected Methods
/**
* Perform the actual JAAS authentication
*/
protected Principal authenticate(String username, CallbackHandler callbackHandler) {
// Establish a LoginContext to use for authentication
try {
LoginContext loginContext = null;
if (appName == null)
appName = "Tomcat";
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
// What if the LoginModule is in the container class loader ?
ClassLoader ocl = null;
if (!isUseContextClassLoader()) {
ocl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
try {
Configuration config = getConfig();
loginContext = new LoginContext(appName, null, callbackHandler, config);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return (null);
} finally {
if (!isUseContextClassLoader()) {
Thread.currentThread().setContextClassLoader(ocl);
}
}
if (log.isDebugEnabled())
log.debug("Login context created " + username);
// Negotiate a login via this LoginContext
Subject subject = null;
try {
loginContext.login();
subject = loginContext.getSubject();
if (subject == null) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", username));
return (null);
}
} catch (AccountExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.accountExpired", username));
return (null);
} catch (CredentialExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.credentialExpired", username));
return (null);
} catch (FailedLoginException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", username));
return (null);
} catch (LoginException e) {
log.warn(sm.getString("jaasRealm.loginException", username), e);
return (null);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return (null);
}
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.loginContextCreated", username));
// Return the appropriate Principal for this authenticated Subject
Principal principal = createPrincipal(username, subject, loginContext);
if (principal == null) {
log.debug(sm.getString("jaasRealm.authenticateFailure", username));
return (null);
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
}
return (principal);
} catch (Throwable t) {
log.error("error ", t);
return null;
}
}
Example 66
Project: airavata-master File: MyProxyLogon.java View source code |
/**
* Logs on to the MyProxy server by issuing the MyProxy GET command.
*/
public void logon() throws IOException, GeneralSecurityException {
String line;
char response;
if (state != State.CONNECTED) {
connect();
}
socketOut.write('0');
socketOut.flush();
socketOut.write(VERSION.getBytes());
socketOut.write('\n');
socketOut.write(GETCOMMAND.getBytes());
socketOut.write('\n');
socketOut.write(USERNAME.getBytes());
socketOut.write(username.getBytes());
socketOut.write('\n');
socketOut.write(PASSPHRASE.getBytes());
socketOut.write(new String(passphrase).getBytes());
socketOut.write('\n');
socketOut.write(LIFETIME.getBytes());
socketOut.write(Integer.toString(lifetime).getBytes());
socketOut.write('\n');
if (credname != null) {
socketOut.write(CREDNAME.getBytes());
socketOut.write(credname.getBytes());
socketOut.write('\n');
}
socketOut.flush();
line = readLine(socketIn);
if (line == null) {
throw new EOFException();
}
if (!line.equals(VERSION)) {
throw new ProtocolException("bad MyProxy protocol VERSION string: " + line);
}
line = readLine(socketIn);
if (line == null) {
throw new EOFException();
}
if (!line.startsWith(RESPONSE) || line.length() != RESPONSE.length() + 1) {
throw new ProtocolException("bad MyProxy protocol RESPONSE string: " + line);
}
response = line.charAt(RESPONSE.length());
if (response == '1') {
StringBuffer errString;
errString = new StringBuffer("MyProxy logon failed");
while ((line = readLine(socketIn)) != null) {
if (line.startsWith(ERROR)) {
errString.append('\n');
errString.append(line.substring(ERROR.length()));
}
}
throw new FailedLoginException(errString.toString());
} else if (response == '2') {
throw new ProtocolException("MyProxy authorization RESPONSE not implemented");
} else if (response != '0') {
throw new ProtocolException("unknown MyProxy protocol RESPONSE string: " + line);
}
while ((line = readLine(socketIn)) != null) {
if (line.startsWith(TRUSTROOTS)) {
String filenameList = line.substring(TRUSTROOTS.length());
trustrootFilenames = filenameList.split(",");
trustrootData = new String[trustrootFilenames.length];
for (int i = 0; i < trustrootFilenames.length; i++) {
String lineStart = "FILEDATA_" + trustrootFilenames[i] + "=";
line = readLine(socketIn);
if (line == null) {
throw new EOFException();
}
if (!line.startsWith(lineStart)) {
throw new ProtocolException("bad MyProxy protocol RESPONSE: expecting " + lineStart + " but received " + line);
}
trustrootData[i] = new String(Base64.decode(line.substring(lineStart.length())));
}
}
}
state = State.LOGGEDON;
}
Example 67
Project: astroboa-master File: RepositoryDao.java View source code |
private SecurityContext authenticate(AstroboaCredentials credentials, String repositoryId, int currentAuthenticationTokenTimeout, String permanentKey) {
SecurityContext securityContext = null;
Subject subject = null;
try {
CredentialsCallbackHandler callbackHandler = null;
if (credentials != null) {
callbackHandler = new CredentialsCallbackHandler(credentials);
}
IdentityStoreContextHolder.setActiveRepositoryId(repositoryId);
AstroboaLogin astroboaLogin = new AstroboaLogin(callbackHandler, identityStore, this);
subject = astroboaLogin.login();
} catch (AccountNotFoundException e) {
throw new CmsLoginInvalidUsernameException(e);
} catch (FailedLoginException e) {
throw new CmsInvalidPasswordException(e);
} catch (AccountLockedException e) {
throw new CmsLoginAccountLockedException(e);
} catch (AccountExpiredException e) {
throw new CmsLoginAccountExpiredException(e);
} catch (CredentialNotFoundException e) {
throw new CmsInvalidPasswordException(e);
} catch (CredentialExpiredException e) {
throw new CmsLoginPasswordExpiredException(e);
} catch (LoginException e) {
throw new CmsException(e);
} catch (CmsException e) {
throw e;
} catch (Throwable t) {
throw new CmsException(t);
} finally {
IdentityStoreContextHolder.clear();
}
authorizeSubject(subject, repositoryId);
try {
String authenticationToken = createAuthenticationToken(subject, repositoryId, permanentKey);
securityContext = new SecurityContext(authenticationToken, subject, currentAuthenticationTokenTimeout, getAvailableRepositoryIds());
if (logger.isDebugEnabled()) {
logger.debug("Successfull authentication: Token {} , Subject {} for Thread {}", new Object[] { authenticationToken, subject, Thread.currentThread() });
}
return securityContext;
} catch (NoSuchAlgorithmException e) {
throw new CmsException(e);
}
}
Example 68
Project: bonita-web-master File: ConsoleIdentityLoginModule.java View source code |
/**
* Method to authenticate a Subject (phase 1). The implementation of this
* method authenticates a Subject. For example, it may prompt for Subject
* information such as a username and password and then attempt to verify the
* password. This method saves the result of the authentication attempt as
* private state within the LoginModule.
*
* @return true if the authentication succeeded, or false if this LoginModule
* should be ignored.
* @throws LoginException
* if the authentication fails
*/
@Override
public boolean login() throws LoginException {
if (this.debug) {
System.err.println("[" + ConsoleIdentityLoginModule.class.getName() + "] login() - preparing - step 1");
}
try {
final Map<String, Object> loggingsArgs = getSharedState();
final Map<String, Callback> callbacks = getPromptCallbacks(loggingsArgs);
if (!callbacks.isEmpty()) {
if (this.debug) {
System.err.println("[" + ConsoleIdentityLoginModule.class.getName() + "] login() - callback - step 2");
}
this.callbackHandler.handle(callbacks.values().toArray(new Callback[0]));
adjustLoggingsArgs(callbacks, loggingsArgs);
}
if (isDebug()) {
System.err.println("[" + ConsoleIdentityLoginModule.class.getName() + "] login() - authenticating - step 3");
}
final APISession aAPISession = (loggingsArgs.containsKey(JAVAX_SECURITY_AUTH_LOGIN_NAME)) ? doLogin(loggingsArgs) : null;
if (isDebug()) {
System.err.println("[" + ConsoleIdentityLoginModule.class.getName() + "] login() - storing data - step 4");
}
if (aAPISession != null) {
this.id = (String) getSharedState().get(JAVAX_SECURITY_AUTH_LOGIN_NAME);
}
if (isDebug()) {
System.err.println("[" + ConsoleIdentityLoginModule.class.getName() + "] login() - returning - step 5");
}
if (this.id == null) {
throw new FailedLoginException("id is null");
}
return true;
} catch (final Exception e) {
e.printStackTrace();
final LoginException le = new LoginException();
le.initCause(e);
throw le;
}
}
Example 69
Project: cas-overlay-master File: OpenScienceFrameworkAuthenticationHandler.java View source code |
/**
* Authenticates an Open Science Framework credential.
*
* @param credential the credential object bearing the username, password, etc...
*
* @return HandlerResult resolved from credential on authentication success or null if no principal could be resolved
* from the credential.
*
* @throws GeneralSecurityException On authentication failure.
* @throws PreventedException On the indeterminate case when authentication is prevented.
*/
protected final HandlerResult authenticateInternal(final OpenScienceFrameworkCredential credential) throws GeneralSecurityException, PreventedException {
final String username = credential.getUsername().toLowerCase();
final String plainTextPassword = credential.getPassword();
final String verificationKey = credential.getVerificationKey();
final String oneTimePassword = credential.getOneTimePassword();
final OpenScienceFrameworkUser user = openScienceFrameworkDao.findOneUserByEmail(username);
if (user == null) {
throw new AccountNotFoundException(username + " not found with query");
}
Boolean validPassphrase = Boolean.FALSE;
final String userStatus = verifyUserStatus(user);
if (credential.isRemotePrincipal()) {
// verified through remote principals
validPassphrase = Boolean.TRUE;
} else if (verificationKey != null && verificationKey.equals(user.getVerificationKey())) {
// verified by verification key
validPassphrase = Boolean.TRUE;
} else if (plainTextPassword != null && verifyPassword(plainTextPassword, user.getPassword())) {
// verified by password
validPassphrase = Boolean.TRUE;
}
if (!validPassphrase) {
throw new FailedLoginException(username + ": invalid remote authentication, verification key or password");
}
final OpenScienceFrameworkTimeBasedOneTimePassword timeBasedOneTimePassword = openScienceFrameworkDao.findOneTimeBasedOneTimePasswordByOwnerId(user.getId());
// if the user has set up two factors authentication
if (timeBasedOneTimePassword != null && timeBasedOneTimePassword.getTotpSecret() != null && timeBasedOneTimePassword.isConfirmed() && !timeBasedOneTimePassword.isDeleted()) {
// if no one time password is provided in credential, redirect to `casOtpLoginView`
if (oneTimePassword == null) {
throw new OneTimePasswordRequiredException("Time-based One Time Password required");
}
// verify one time password
try {
final Long longOneTimePassword = Long.valueOf(oneTimePassword);
if (!TotpUtils.checkCode(timeBasedOneTimePassword.getTotpSecretBase32(), longOneTimePassword, TOTP_INTERVAL, TOTP_WINDOW)) {
throw new OneTimePasswordFailedLoginException(username + " invalid time-based one time password");
}
} catch (final Exception e) {
throw new OneTimePasswordFailedLoginException(username + ": invalid time-based one time password");
}
}
// Check user's status, and only ACTIVE user can sign in
if (USER_NOT_CONFIRMED.equals(userStatus)) {
throw new LoginNotAllowedException(username + " is not registered");
} else if (USER_DISABLED.equals(userStatus)) {
throw new AccountDisabledException(username + " is disabled");
} else if (USER_NOT_CLAIMED.equals(userStatus)) {
throw new ShouldNotHappenException(username + " is not claimed");
} else if (USER_MERGED.equals(userStatus)) {
throw new ShouldNotHappenException("Cannot log in to a merged user " + username);
} else if (USER_STATUS_UNKNOWN.equals(userStatus)) {
throw new ShouldNotHappenException(username + " is not active: unknown status");
}
final Map<String, Object> attributes = new HashMap<>();
attributes.put("username", user.getUsername());
attributes.put("givenName", user.getGivenName());
attributes.put("familyName", user.getFamilyName());
// CAS returns the user's GUID to OSF
// Note: GUID is recommended. Do not use user's pimary key or username.
final OpenScienceFrameworkGuid guid = openScienceFrameworkDao.findGuidByUser(user);
return createHandlerResult(credential, this.principalFactory.createPrincipal(guid.getGuid(), attributes), null);
}
Example 70
Project: crowd-jaas-master File: CrowdLoginModule.java View source code |
/**
* @see javax.security.auth.spi.LoginModule#login()
*/
@Override
public boolean login() throws LoginException {
try {
if (callbackHandler == null) {
throw new LoginException("No callback handler");
}
Callback[] callbacks = configureCallbacks();
callbackHandler.handle(callbacks);
String username = ((NameCallback) callbacks[0]).getName();
String password = (String) ((ObjectCallback) callbacks[1]).getObject();
if (username == null || password == null) {
authenticated = false;
}
authenticate(username, password);
authenticated = true;
} catch (Exception e) {
LOG.error("login()", e);
throw new FailedLoginException(e.getMessage());
}
return authenticated;
}
Example 71
Project: Tomcat-master File: JAASRealm.java View source code |
// -------------------------------------------------------- Package Methods
// ------------------------------------------------------ Protected Methods
/**
* Perform the actual JAAS authentication.
* @param username The user name
* @param callbackHandler The callback handler
* @return the associated principal, or <code>null</code> if there is none.
*/
protected Principal authenticate(String username, CallbackHandler callbackHandler) {
// Establish a LoginContext to use for authentication
try {
LoginContext loginContext = null;
if (appName == null)
appName = "Tomcat";
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
// What if the LoginModule is in the container class loader ?
ClassLoader ocl = null;
if (!isUseContextClassLoader()) {
ocl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
try {
Configuration config = getConfig();
loginContext = new LoginContext(appName, null, callbackHandler, config);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return null;
} finally {
if (!isUseContextClassLoader()) {
Thread.currentThread().setContextClassLoader(ocl);
}
}
if (log.isDebugEnabled())
log.debug("Login context created " + username);
// Negotiate a login via this LoginContext
Subject subject = null;
try {
loginContext.login();
subject = loginContext.getSubject();
if (subject == null) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", username));
return null;
}
} catch (AccountExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.accountExpired", username));
return null;
} catch (CredentialExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.credentialExpired", username));
return null;
} catch (FailedLoginException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", username));
return null;
} catch (LoginException e) {
log.warn(sm.getString("jaasRealm.loginException", username), e);
return null;
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return null;
}
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.loginContextCreated", username));
// Return the appropriate Principal for this authenticated Subject
Principal principal = createPrincipal(username, subject, loginContext);
if (principal == null) {
log.debug(sm.getString("jaasRealm.authenticateFailure", username));
return null;
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
}
return principal;
} catch (Throwable t) {
log.error("error ", t);
return null;
}
}
Example 72
Project: tomcat60-master File: JAASRealm.java View source code |
// -------------------------------------------------------- Package Methods
// ------------------------------------------------------ Protected Methods
/**
* Perform the actual JAAS authentication
*/
protected Principal authenticate(String username, CallbackHandler callbackHandler) {
// Establish a LoginContext to use for authentication
try {
LoginContext loginContext = null;
if (appName == null)
appName = "Tomcat";
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.beginLogin", username, appName));
// What if the LoginModule is in the container class loader ?
ClassLoader ocl = null;
if (!isUseContextClassLoader()) {
ocl = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
}
try {
loginContext = new LoginContext(appName, callbackHandler);
} catch (Throwable e) {
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return (null);
} finally {
if (!isUseContextClassLoader()) {
Thread.currentThread().setContextClassLoader(ocl);
}
}
if (log.isDebugEnabled())
log.debug("Login context created " + username);
// Negotiate a login via this LoginContext
Subject subject = null;
try {
loginContext.login();
subject = loginContext.getSubject();
if (subject == null) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", username));
return (null);
}
} catch (AccountExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.accountExpired", username));
return (null);
} catch (CredentialExpiredException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.credentialExpired", username));
return (null);
} catch (FailedLoginException e) {
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.failedLogin", username));
return (null);
} catch (LoginException e) {
log.warn(sm.getString("jaasRealm.loginException", username), e);
return (null);
} catch (Throwable e) {
log.error(sm.getString("jaasRealm.unexpectedError"), e);
return (null);
}
if (log.isDebugEnabled())
log.debug(sm.getString("jaasRealm.loginContextCreated", username));
// Return the appropriate Principal for this authenticated Subject
Principal principal = createPrincipal(username, subject, loginContext);
if (principal == null) {
log.debug(sm.getString("jaasRealm.authenticateFailure", username));
return (null);
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("jaasRealm.authenticateSuccess", username));
}
return (principal);
} catch (Throwable t) {
log.error("error ", t);
return null;
}
}
Example 73
Project: jmxfetch-master File: App.java View source code |
public void doIteration() {
loopCounter++;
Reporter reporter = appConfig.getReporter();
Iterator<Instance> it = instances.iterator();
while (it.hasNext()) {
Instance instance = it.next();
LinkedList<HashMap<String, Object>> metrics;
String instanceStatus = Status.STATUS_OK;
String scStatus = Status.STATUS_OK;
String instanceMessage = null;
int numberOfMetrics = 0;
try {
if (!instance.timeToCollect()) {
LOGGER.debug("it is not time to collect, skipping run for " + instance.getName());
continue;
}
metrics = instance.getMetrics();
numberOfMetrics = metrics.size();
if (numberOfMetrics == 0) {
instanceMessage = "Instance " + instance + " didn't return any metrics";
LOGGER.warn(instanceMessage);
instanceStatus = Status.STATUS_ERROR;
scStatus = Status.STATUS_ERROR;
brokenInstances.add(instance);
} else if (instance.isLimitReached()) {
instanceMessage = "Number of returned metrics is too high for instance: " + instance.getName() + ". Please read http://docs.datadoghq.com/integrations/java/ or get in touch with Datadog " + "Support for more details. Truncating to " + instance.getMaxNumberOfMetrics() + " metrics.";
instanceStatus = Status.STATUS_WARNING;
// We don't want to log the warning at every iteration so we use this custom logger.
CustomLogger.laconic(LOGGER, Level.WARN, instanceMessage, 0);
}
if (numberOfMetrics > 0)
reporter.sendMetrics(metrics, instance.getName());
} catch (IOException e) {
instanceMessage = "Unable to refresh bean list for instance " + instance;
LOGGER.warn(instanceMessage, e);
instanceStatus = Status.STATUS_ERROR;
scStatus = Status.STATUS_ERROR;
brokenInstances.add(instance);
}
this.reportStatus(appConfig, reporter, instance, numberOfMetrics, instanceMessage, instanceStatus);
this.sendServiceCheck(reporter, instance, instanceMessage, scStatus);
}
// Iterate over broken" instances to fix them by resetting them
it = brokenInstances.iterator();
while (it.hasNext()) {
Instance instance = it.next();
// Clearing rates aggregator so we won't compute wrong rates if we can reconnect
reporter.clearRatesAggregator(instance.getName());
LOGGER.warn("Instance " + instance + " didn't return any metrics." + "Maybe the server got disconnected ? Trying to reconnect.");
// Remove the broken instance from the good instance list so jmxfetch won't try to collect metrics from this broken instance during next collection
instance.cleanUp();
instances.remove(instance);
// Resetting the instance
Instance newInstance = new Instance(instance, appConfig);
try {
// Try to reinit the connection and force to renew it
LOGGER.info("Trying to reconnect to: " + newInstance);
newInstance.init(true);
// If we are here, the connection succeeded, the instance is fixed. It can be readded to the good instances list
instances.add(newInstance);
it.remove();
} catch (Exception e) {
String warning = null;
if (e instanceof IOException) {
warning = CANNOT_CONNECT_TO_INSTANCE + instance + ". Is a JMX Server running at this address?";
LOGGER.warn(warning);
} else if (e instanceof SecurityException) {
warning = CANNOT_CONNECT_TO_INSTANCE + instance + " because of bad credentials. Please check your credentials";
LOGGER.warn(warning);
} else if (e instanceof FailedLoginException) {
warning = CANNOT_CONNECT_TO_INSTANCE + instance + " because of bad credentials. Please check your credentials";
LOGGER.warn(warning);
} else {
warning = CANNOT_CONNECT_TO_INSTANCE + instance + " for an unknown reason." + e.getMessage();
LOGGER.fatal(warning, e);
}
this.reportStatus(appConfig, reporter, instance, 0, warning, Status.STATUS_ERROR);
this.sendServiceCheck(reporter, instance, warning, Status.STATUS_ERROR);
}
}
try {
appConfig.getStatus().flush();
} catch (Exception e) {
LOGGER.error("Unable to flush stats.", e);
}
}
Example 74
Project: karaf-cave-master File: CaveMavenServlet.java View source code |
public Subject doAuthenticate(final String username, final String password, final String role) {
try {
Subject subject = new Subject();
LoginContext loginContext = new LoginContext(realm, subject, new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword(password.toCharArray());
} else {
throw new UnsupportedCallbackException(callback);
}
}
}
});
loginContext.login();
if (role != null && role.length() > 0) {
String clazz = "org.apache.karaf.jaas.boot.principal.RolePrincipal";
String name = role;
int idx = role.indexOf(':');
if (idx > 0) {
clazz = role.substring(0, idx);
name = role.substring(idx + 1);
}
boolean found = false;
for (Principal p : subject.getPrincipals()) {
if (p.getClass().getName().equals(clazz) && p.getName().equals(name)) {
found = true;
break;
}
}
if (!found) {
throw new FailedLoginException("User does not have the required role " + role);
}
}
return subject;
} catch (AccountException e) {
LOGGER.warn("Account failure", e);
return null;
} catch (LoginException e) {
LOGGER.debug("Login failed", e);
return null;
}
}
Example 75
Project: picketbox-master File: UsernamePasswordLoginModule.java View source code |
/** Perform the authentication of the username and password. */ @Override @SuppressWarnings("unchecked") public boolean login() throws LoginException { // See if shared credentials exist if (super.login() == true) { // Setup our view of the user Object username = sharedState.get("javax.security.auth.login.name"); if (username instanceof Principal) identity = (Principal) username; else { String name = username.toString(); try { identity = createIdentity(name); } catch (Exception e) { LoginException le = PicketBoxMessages.MESSAGES.failedToCreatePrincipal(e.getLocalizedMessage()); le.initCause(e); throw le; } } Object password = sharedState.get("javax.security.auth.login.password"); if (password instanceof char[]) credential = (char[]) password; else if (password != null) { String tmp = password.toString(); credential = tmp.toCharArray(); } return true; } super.loginOk = false; String[] info = getUsernameAndPassword(); String username = info[0]; String password = info[1]; // validate the retrieved username and password. if (this.inputValidator != null) { try { this.inputValidator.validateUsernameAndPassword(username, password); } catch (InputValidationException ive) { throw new FailedLoginException(ive.getLocalizedMessage()); } } if (username == null && password == null) { identity = unauthenticatedIdentity; PicketBoxLogger.LOGGER.traceUsingUnauthIdentity(identity != null ? identity.getName() : null); } if (identity == null) { try { identity = createIdentity(username); } catch (Exception e) { LoginException le = PicketBoxMessages.MESSAGES.failedToCreatePrincipal(e.getLocalizedMessage()); le.initCause(e); throw le; } // Hash the user entered password if password hashing is in use if (hashAlgorithm != null && hashUserPassword == true) password = createPasswordHash(username, password, DIGEST_CALLBACK); // Validate the password supplied by the subclass String expectedPassword = getUsersPassword(); //Check if the password is vaultified if (SecurityVaultUtil.isVaultFormat(expectedPassword)) { try { expectedPassword = SecurityVaultUtil.getValueAsString(expectedPassword); } catch (SecurityVaultException e) { LoginException le = PicketBoxMessages.MESSAGES.unableToGetPasswordFromVault(); le.initCause(e); throw le; } } // Allow the storeDigestCallback to hash the expected password if (hashAlgorithm != null && hashStorePassword == true) expectedPassword = createPasswordHash(username, expectedPassword, STORE_DIGEST_CALLBACK); if (validatePassword(password, expectedPassword) == false) { Throwable ex = getValidateError(); FailedLoginException fle = PicketBoxMessages.MESSAGES.invalidPassword(); PicketBoxLogger.LOGGER.debugBadPasswordForUsername(username); if (ex != null && this.throwValidateError) fle.initCause(ex); throw fle; } } if (getUseFirstPass() == true) { // Add the principal and password to the shared state map sharedState.put("javax.security.auth.login.name", identity); sharedState.put("javax.security.auth.login.password", credential); } super.loginOk = true; PicketBoxLogger.LOGGER.traceEndLogin(super.loginOk); return true; }
Example 76
Project: classlib6-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @exception LoginException if the login operation fails * @exception SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11 Token [providerName] Password: ")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 77
Project: ikvm-openjdk-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @exception LoginException if the login operation fails * @exception SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11 Token [providerName] Password: ")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 78
Project: JDK-master File: KeyStoreLoginModule.java View source code |
/** Get the credentials from the KeyStore. */ private void getKeyStoreInfo() throws LoginException { /* Get KeyStore instance */ try { if (keyStoreProvider == null) { keyStore = KeyStore.getInstance(keyStoreType); } else { keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider); } } catch (KeyStoreException e) { LoginException le = new LoginException("The specified keystore type was not available"); le.initCause(e); throw le; } catch (NoSuchProviderException e) { LoginException le = new LoginException("The specified keystore provider was not available"); le.initCause(e); throw le; } /* Load KeyStore contents from file */ InputStream in = null; try { if (nullStream) { // if using protected auth path, keyStorePassword will be null keyStore.load(null, keyStorePassword); } else { in = new URL(keyStoreURL).openStream(); keyStore.load(in, keyStorePassword); } } catch (MalformedURLException e) { LoginException le = new LoginException("Incorrect keyStoreURL option"); le.initCause(e); throw le; } catch (GeneralSecurityException e) { LoginException le = new LoginException("Error initializing keystore"); le.initCause(e); throw le; } catch (IOException e) { LoginException le = new LoginException("Error initializing keystore"); le.initCause(e); throw le; } finally { if (in != null) { try { in.close(); } catch (IOException ioe) { LoginException le = new LoginException("Error initializing keystore"); le.initCause(ioe); throw le; } } } /* Get certificate chain and create a certificate path */ try { fromKeyStore = keyStore.getCertificateChain(keyStoreAlias); if (fromKeyStore == null || fromKeyStore.length == 0 || !(fromKeyStore[0] instanceof X509Certificate)) { throw new FailedLoginException("Unable to find X.509 certificate chain in keystore"); } else { LinkedList<Certificate> certList = new LinkedList<>(); for (int i = 0; i < fromKeyStore.length; i++) { certList.add(fromKeyStore[i]); } CertificateFactory certF = CertificateFactory.getInstance("X.509"); certP = certF.generateCertPath(certList); } } catch (KeyStoreException e) { LoginException le = new LoginException("Error using keystore"); le.initCause(e); throw le; } catch (CertificateException ce) { LoginException le = new LoginException("Error: X.509 Certificate type unavailable"); le.initCause(ce); throw le; } /* Get principal and keys */ try { X509Certificate certificate = (X509Certificate) fromKeyStore[0]; principal = new javax.security.auth.x500.X500Principal(certificate.getSubjectDN().getName()); // if token, privateKeyPassword will be null Key privateKey = keyStore.getKey(keyStoreAlias, privateKeyPassword); if (privateKey == null || !(privateKey instanceof PrivateKey)) { throw new FailedLoginException("Unable to recover key from keystore"); } privateCredential = new X500PrivateCredential(certificate, (PrivateKey) privateKey, keyStoreAlias); } catch (KeyStoreException e) { LoginException le = new LoginException("Error using keystore"); le.initCause(e); throw le; } catch (NoSuchAlgorithmException e) { LoginException le = new LoginException("Error using keystore"); le.initCause(e); throw le; } catch (UnrecoverableKeyException e) { FailedLoginException fle = new FailedLoginException("Unable to recover key from keystore"); fle.initCause(e); throw fle; } if (debug) { debugPrint("principal=" + principal + "\n certificate=" + privateCredential.getCertificate() + "\n alias =" + privateCredential.getAlias()); } }
Example 79
Project: MBeanSelector-master File: JConsole.java View source code |
private String errorMessage(Exception ex) {
String msg = Resources.getText("Connection failed");
if (ex instanceof IOException || ex instanceof SecurityException) {
Throwable cause = null;
Throwable c = ex.getCause();
while (c != null) {
cause = c;
c = c.getCause();
}
if (cause instanceof ConnectException) {
return msg + ": " + cause.getMessage();
} else if (cause instanceof UnknownHostException) {
return Resources.getText("Unknown Host", cause.getMessage());
} else if (cause instanceof NoRouteToHostException) {
return msg + ": " + cause.getMessage();
} else if (cause instanceof FailedLoginException) {
return msg + ": " + cause.getMessage();
} else if (cause instanceof SSLHandshakeException) {
return msg + ": " + cause.getMessage();
}
} else if (ex instanceof MalformedURLException) {
return Resources.getText("Invalid URL", ex.getMessage());
}
return msg + ": " + ex.getMessage();
}
Example 80
Project: zaproxy-master File: OptionsCertificatePanel.java View source code |
//GEN-LAST:event_showActiveCertificateButtonActionPerformed
private //GEN-FIRST:event_addPkcs11ButtonActionPerformed
void addPkcs11ButtonActionPerformed(//GEN-FIRST:event_addPkcs11ButtonActionPerformed
java.awt.event.ActionEvent evt) {
String name = null;
try {
final int indexSelectedDriver = driverComboBox.getSelectedIndex();
name = driverConfig.getNames().get(indexSelectedDriver);
if (name.equals("")) {
return;
}
String library = driverConfig.getPaths().get(indexSelectedDriver);
if (library.equals("")) {
return;
}
int slot = driverConfig.getSlots().get(indexSelectedDriver).intValue();
if (slot < 0) {
return;
}
int slotListIndex = driverConfig.getSlotIndexes().get(indexSelectedDriver).intValue();
if (slotListIndex < 0) {
return;
}
String kspass = new String(pkcs11PasswordField.getPassword());
if (kspass.equals("")) {
kspass = null;
}
PCKS11ConfigurationBuilder confBuilder = PKCS11Configuration.builder();
confBuilder.setName(name).setLibrary(library);
if (usePkcs11ExperimentalSliSupportCheckBox.isSelected()) {
confBuilder.setSlotListIndex(slotListIndex);
} else {
confBuilder.setSlotId(slot);
}
int ksIndex = contextManager.initPKCS11(confBuilder.build(), kspass);
if (ksIndex == -1) {
logger.error("The required PKCS#11 provider is not available (" + SSLContextManager.SUN_PKCS11_CANONICAL_CLASS_NAME + " or " + SSLContextManager.IBM_PKCS11_CONONICAL_CLASS_NAME + ").");
showErrorMessageSunPkcs11ProviderNotAvailable();
return;
}
// The PCKS11 driver/smartcard was initialized properly: reset login attempts
login_attempts = 0;
keyStoreListModel.insertElementAt(contextManager.getKeyStoreDescription(ksIndex), ksIndex);
// Issue 182
retry = true;
certificatejTabbedPane.setSelectedIndex(0);
selectFirstAliasOfKeyStore(ksIndex);
driverComboBox.setSelectedIndex(-1);
pkcs11PasswordField.setText("");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof ProviderException) {
if ("Error parsing configuration".equals(e.getCause().getMessage())) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
} else if ("Initialization failed".equals(e.getCause().getMessage())) {
if (retry) {
retry = false;
addPkcs11ButtonActionPerformed(evt);
} else {
JOptionPane.showMessageDialog(null, new String[] { Constant.messages.getString("options.cert.error"), Constant.messages.getString("options.cert.error.pkcs11") }, Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
retry = true;
logger.warn("Couldn't add key from " + name, e);
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} catch (java.io.IOException e) {
if (e.getMessage().equals("load failed") && e.getCause().getClass().getName().equals("javax.security.auth.login.FailedLoginException")) {
login_attempts++;
String attempts = " (" + login_attempts + "/" + MAX_LOGIN_ATTEMPTS + ") ";
if (login_attempts == (MAX_LOGIN_ATTEMPTS - 1)) {
JOptionPane.showMessageDialog(null, new String[] { Constant.messages.getString("options.cert.error"), Constant.messages.getString("options.cert.error.wrongpassword"), Constant.messages.getString("options.cert.error.wrongpasswordlast"), attempts }, Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password" + attempts + ": " + name + " *LAST TRY BEFORE BLOCKING*");
} else {
JOptionPane.showMessageDialog(null, new String[] { Constant.messages.getString("options.cert.error"), Constant.messages.getString("options.cert.error.wrongpassword"), attempts }, Constant.messages.getString("options.cert.label.client.cert"), JOptionPane.ERROR_MESSAGE);
logger.warn("PKCS#11: Incorrect PIN or password" + attempts + ": " + name);
}
} else {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
}
} catch (KeyStoreException e) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(false, name, e);
} catch (Exception e) {
logAndShowGenericErrorMessagePkcs11CouldNotBeAdded(true, name, e);
}
}
Example 81
Project: barchart-udt-master File: SunPKCS11.java View source code |
/** * Log in to this provider. * * <p> If the token expects a PIN to be supplied by the caller, * the <code>handler</code> implementation must support * a <code>PasswordCallback</code>. * * <p> To determine if the token supports a protected authentication path, * the CK_TOKEN_INFO flag, CKF_PROTECTED_AUTHENTICATION_PATH, is consulted. * * @param subject this parameter is ignored * @param handler the <code>CallbackHandler</code> used by * this provider to communicate with the caller * * @exception LoginException if the login operation fails * @exception SecurityException if the does not pass a security check for * <code>SecurityPermission("authProvider.<i>name</i>")</code>, * where <i>name</i> is the value returned by * this provider's <code>getName</code> method */ public void login(Subject subject, CallbackHandler handler) throws LoginException { // security check SecurityManager sm = System.getSecurityManager(); if (sm != null) { if (debug != null) { debug.println("checking login permission"); } sm.checkPermission(new SecurityPermission("authProvider." + this.getName())); } if (hasValidToken() == false) { throw new LoginException("No token present"); } if ((token.tokenInfo.flags & CKF_LOGIN_REQUIRED) == 0) { if (debug != null) { debug.println("login operation not required for token - " + "ignoring login request"); } return; } try { if (token.isLoggedInNow(null)) { // user already logged in if (debug != null) { debug.println("user already logged in"); } return; } } catch (PKCS11Exception e) { } // get the pin if necessary char[] pin = null; if ((token.tokenInfo.flags & CKF_PROTECTED_AUTHENTICATION_PATH) == 0) { // get password CallbackHandler myHandler = getCallbackHandler(handler); if (myHandler == null) { // XXX PolicyTool is dependent on this message text throw new LoginException("no password provided, and no callback handler " + "available for retrieving password"); } java.text.MessageFormat form = new java.text.MessageFormat(ResourcesMgr.getString("PKCS11 Token [providerName] Password: ")); Object[] source = { getName() }; PasswordCallback pcall = new PasswordCallback(form.format(source), false); Callback[] callbacks = { pcall }; try { myHandler.handle(callbacks); } catch (Exception e) { LoginException le = new LoginException("Unable to perform password callback"); le.initCause(e); throw le; } pin = pcall.getPassword(); pcall.clearPassword(); if (pin == null) { if (debug != null) { debug.println("caller passed NULL pin"); } } } // perform token login Session session = null; try { session = token.getOpSession(); // pin is NULL if using CKF_PROTECTED_AUTHENTICATION_PATH p11.C_Login(session.id(), CKU_USER, pin); if (debug != null) { debug.println("login succeeded"); } } catch (PKCS11Exception pe) { if (pe.getErrorCode() == CKR_USER_ALREADY_LOGGED_IN) { if (debug != null) { debug.println("user already logged in"); } return; } else if (pe.getErrorCode() == CKR_PIN_INCORRECT) { FailedLoginException fle = new FailedLoginException(); fle.initCause(pe); throw fle; } else { LoginException le = new LoginException(); le.initCause(pe); throw le; } } finally { token.releaseSession(session); if (pin != null) { Arrays.fill(pin, ' '); } } // we do not store the PIN in the subject for now }
Example 82
Project: eid-applet-master File: Controller.java View source code |
public Object run() {
printEnvironment();
try {
Applet applet = this.runtime.getApplet();
String language = applet.getParameter(Applet.LANGUAGE_PARAM);
HelloMessage helloMessage = new HelloMessage(language);
Object resultMessage = sendMessage(helloMessage);
if (resultMessage instanceof CheckClientMessage) {
addDetailMessage("Need to check the client secure environment...");
ClientEnvironmentMessage clientEnvMessage = new ClientEnvironmentMessage();
clientEnvMessage.javaVersion = System.getProperty("java.version");
clientEnvMessage.javaVendor = System.getProperty("java.vendor");
clientEnvMessage.osName = System.getProperty("os.name");
clientEnvMessage.osArch = System.getProperty("os.arch");
clientEnvMessage.osVersion = System.getProperty("os.version");
clientEnvMessage.readerList = this.pcscEidSpi.getReaderList();
clientEnvMessage.navigatorAppName = this.runtime.getParameter("NavigatorAppName");
clientEnvMessage.navigatorAppVersion = this.runtime.getParameter("NavigatorAppVersion");
clientEnvMessage.navigatorUserAgent = this.runtime.getParameter("NavigatorUserAgent");
resultMessage = sendMessage(clientEnvMessage);
if (resultMessage instanceof InsecureClientMessage) {
InsecureClientMessage insecureClientMessage = (InsecureClientMessage) resultMessage;
if (insecureClientMessage.warnOnly) {
int result = JOptionPane.showConfirmDialog(this.view.getParentComponent(), "Your system has been marked as insecure client environment.\n" + "Do you want to continue the eID operation?", "Insecure Client Environment", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
if (JOptionPane.OK_OPTION != result) {
setStatusMessage(Status.ERROR, MESSAGE_ID.SECURITY_ERROR);
addDetailMessage("insecure client environment");
return null;
}
resultMessage = sendMessage(new ContinueInsecureMessage());
} else {
JOptionPane.showMessageDialog(this.view.getParentComponent(), "Your system has been marked as insecure client environment.", "Insecure Client Environment", JOptionPane.ERROR_MESSAGE);
setStatusMessage(Status.ERROR, MESSAGE_ID.SECURITY_ERROR);
addDetailMessage("received an insecure client environment message");
return null;
}
}
}
if (resultMessage instanceof AdministrationMessage) {
AdministrationMessage administrationMessage = (AdministrationMessage) resultMessage;
boolean changePin = administrationMessage.changePin;
boolean unblockPin = administrationMessage.unblockPin;
boolean removeCard = administrationMessage.removeCard;
boolean logoff = administrationMessage.logoff;
boolean requireSecureReader = administrationMessage.requireSecureReader;
addDetailMessage("change pin: " + changePin);
addDetailMessage("unblock pin: " + unblockPin);
addDetailMessage("remove card: " + removeCard);
addDetailMessage("logoff: " + logoff);
addDetailMessage("require secure reader: " + requireSecureReader);
administration(unblockPin, changePin, logoff, removeCard, requireSecureReader);
}
if (resultMessage instanceof FilesDigestRequestMessage) {
FilesDigestRequestMessage filesDigestRequestMessage = (FilesDigestRequestMessage) resultMessage;
resultMessage = performFilesDigestOperation(filesDigestRequestMessage.digestAlgo);
}
if (resultMessage instanceof SignCertificatesRequestMessage) {
SignCertificatesRequestMessage signCertificatesRequestMessage = (SignCertificatesRequestMessage) resultMessage;
SignCertificatesDataMessage signCertificatesDataMessage = performSignCertificatesOperation(signCertificatesRequestMessage);
resultMessage = sendMessage(signCertificatesDataMessage);
}
if (resultMessage instanceof SignRequestMessage) {
SignRequestMessage signRequestMessage = (SignRequestMessage) resultMessage;
resultMessage = performEidSignOperation(signRequestMessage);
}
if (resultMessage instanceof AuthenticationRequestMessage) {
AuthenticationRequestMessage authnRequest = (AuthenticationRequestMessage) resultMessage;
resultMessage = performEidAuthnOperation(authnRequest);
}
if (resultMessage instanceof AuthSignRequestMessage) {
AuthSignRequestMessage authSignRequestMessage = (AuthSignRequestMessage) resultMessage;
resultMessage = performAuthnSignOperation(authSignRequestMessage);
}
if (resultMessage instanceof IdentificationRequestMessage) {
IdentificationRequestMessage identificationRequestMessage = (IdentificationRequestMessage) resultMessage;
addDetailMessage("include address: " + identificationRequestMessage.includeAddress);
addDetailMessage("include photo: " + identificationRequestMessage.includePhoto);
addDetailMessage("include integrity data: " + identificationRequestMessage.includeIntegrityData);
addDetailMessage("include certificates: " + identificationRequestMessage.includeCertificates);
addDetailMessage("remove card: " + identificationRequestMessage.removeCard);
addDetailMessage("identity data usage: " + identificationRequestMessage.identityDataUsage);
resultMessage = performEidIdentificationOperation(identificationRequestMessage.includeAddress, identificationRequestMessage.includePhoto, identificationRequestMessage.includeIntegrityData, identificationRequestMessage.includeCertificates, identificationRequestMessage.removeCard, identificationRequestMessage.identityDataUsage);
}
if (resultMessage instanceof FinishedMessage) {
FinishedMessage finishedMessage = (FinishedMessage) resultMessage;
if (null != finishedMessage.errorCode) {
switch(finishedMessage.errorCode) {
case CERTIFICATE:
addDetailMessage("something wrong with your certificate");
setStatusMessage(Status.ERROR, MESSAGE_ID.SECURITY_ERROR);
return null;
case CERTIFICATE_EXPIRED:
setStatusMessage(Status.ERROR, MESSAGE_ID.CERTIFICATE_EXPIRED_ERROR);
return null;
case CERTIFICATE_REVOKED:
setStatusMessage(Status.ERROR, MESSAGE_ID.CERTIFICATE_REVOKED_ERROR);
return null;
case CERTIFICATE_NOT_TRUSTED:
setStatusMessage(Status.ERROR, MESSAGE_ID.CERTIFICATE_NOT_TRUSTED);
return null;
case AUTHORIZATION:
setStatusMessage(Status.ERROR, MESSAGE_ID.AUTHORIZATION_ERROR);
this.runtime.gotoAuthorizationErrorPage();
return null;
default:
}
setStatusMessage(Status.ERROR, MESSAGE_ID.GENERIC_ERROR);
addDetailMessage("error code @ finish: " + finishedMessage.errorCode);
return null;
}
}
} catch (SecurityException e) {
setStatusMessage(Status.ERROR, MESSAGE_ID.SECURITY_ERROR);
addDetailMessage("error: " + e.getMessage());
return null;
} catch (Throwable e) {
addDetailMessage("error: " + e.getMessage());
addDetailMessage("error type: " + e.getClass().getName());
StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
addDetailMessage("at " + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName() + ":" + stackTraceElement.getLineNumber());
}
Throwable cause = e.getCause();
if (null != cause) {
addDetailMessage("Caused by: " + cause.getClass().getName() + ": " + cause.getMessage());
stackTrace = cause.getStackTrace();
for (StackTraceElement stackTraceElement : stackTrace) {
addDetailMessage("at " + stackTraceElement.getClassName() + "." + stackTraceElement.getMethodName() + ":" + stackTraceElement.getLineNumber());
}
if (FailedLoginException.class == cause.getClass()) {
setStatusMessage(Status.ERROR, MESSAGE_ID.PIN_INCORRECT);
return null;
}
if (LoginException.class == cause.getClass()) {
if (null == cause.getMessage()) {
setStatusMessage(Status.ERROR, MESSAGE_ID.PIN_BLOCKED);
return null;
}
setStatusMessage(Status.ERROR, MESSAGE_ID.SECURITY_ERROR);
return null;
}
}
if ("javax.smartcardio.CardException".equals(e.getClass().getName())) {
setStatusMessage(Status.ERROR, MESSAGE_ID.CARD_ERROR);
addDetailMessage("card error: " + e.getMessage());
return null;
}
setStatusMessage(Status.ERROR, MESSAGE_ID.GENERIC_ERROR);
return null;
}
setStatusMessage(Status.NORMAL, MESSAGE_ID.DONE);
this.runtime.gotoTargetPage();
return null;
}
Example 83
Project: sling-master File: XingLoginLoginModulePlugin.java View source code |
@Override
public int impersonate(final Principal principal, final Credentials credentials) throws RepositoryException, FailedLoginException {
logger.debug("impersonate({}, {})", principal, credentials);
return LoginModulePlugin.IMPERSONATION_DEFAULT;
}