下面列出了org.apache.hadoop.mapreduce.lib.input.InvalidInputException#javax.security.auth.login.LoginException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static void main(String[] args) throws Exception {
OneKDC kdc = new OneKDC(null);
kdc.writeJAASConf();
KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
"default_tkt_enctypes=des-cbc-md5",
"default_tgs_enctypes=des-cbc-md5",
"permitted_enctypes=des-cbc-md5");
Config.refresh();
try {
Context.fromJAAS("client");
throw new Exception("What?");
} catch (LoginException le) {
// This is OK
}
}
/**
* Commit phase of login
*/
public boolean commit() throws LoginException {
if (isAuthSucceeded()) { // Check if authentication succeeded
// External UID must exist in order to get manager info
if (iExternalUid == null || iExternalUid.trim().length() == 0)
throw new LoginException("External UID not found");
getSubject().getPrincipals().add(new AuthenticatedUser(getUser(), iExternalUid));
setCommitSucceeded(true);
return true;
} else { // Authentication failed - do not commit
reset();
return false;
}
}
/**
* Create the RM registry operations as the current user
* @return the service
* @throws LoginException
* @throws FileNotFoundException
*/
public RMRegistryOperationsService startRMRegistryOperations() throws
LoginException, IOException, InterruptedException {
// kerberos
secureConf.set(KEY_REGISTRY_CLIENT_AUTH,
REGISTRY_CLIENT_AUTH_KERBEROS);
secureConf.set(KEY_REGISTRY_CLIENT_JAAS_CONTEXT, ZOOKEEPER_CLIENT_CONTEXT);
RMRegistryOperationsService registryOperations = zookeeperUGI.doAs(
new PrivilegedExceptionAction<RMRegistryOperationsService>() {
@Override
public RMRegistryOperationsService run() throws Exception {
RMRegistryOperationsService operations
= new RMRegistryOperationsService("rmregistry", secureZK);
addToTeardown(operations);
operations.init(secureConf);
LOG.info(operations.bindingDiagnosticDetails());
operations.start();
return operations;
}
});
return registryOperations;
}
/**
* Shutdown pool, close all open connections.
* If a principal is authenticated with a KDC, that principal is logged out.
*
* If a @{@link LoginException} occurs while attempting to log out the @{@link org.apache.nifi.security.krb.KerberosUser},
* an attempt will still be made to shut down the pool and close open connections.
*
* @throws SQLException if there is an error while closing open connections
* @throws LoginException if there is an error during the principal log out, and will only be thrown if there was
* no exception while closing open connections
*/
@OnDisabled
public void shutdown() throws SQLException, LoginException {
try {
if (kerberosUser != null) {
kerberosUser.logout();
}
} finally {
kerberosUser = null;
try {
if (dataSource != null) {
dataSource.close();
}
} finally {
dataSource = null;
}
}
}
/**
* Retrieves the ServiceCreds for the specified server principal from
* the Subject in the specified AccessControlContext. If not found, and if
* useSubjectCredsOnly is false, then obtain from a LoginContext.
*
* NOTE: This method is also used by JSSE Kerberos Cipher Suites
*/
public static ServiceCreds getServiceCreds(GSSCaller caller,
String serverPrincipal, AccessControlContext acc)
throws LoginException {
Subject accSubj = Subject.getSubject(acc);
ServiceCreds sc = null;
if (accSubj != null) {
sc = ServiceCreds.getInstance(accSubj, serverPrincipal);
}
if (sc == null && !GSSUtil.useSubjectCredsOnly(caller)) {
Subject subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
sc = ServiceCreds.getInstance(subject, serverPrincipal);
}
return sc;
}
public static void main(String[] args) throws Exception {
OneKDC kdc = new OneKDC(null);
kdc.writeJAASConf();
KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
"default_tkt_enctypes=des-cbc-md5",
"default_tgs_enctypes=des-cbc-md5",
"permitted_enctypes=des-cbc-md5");
Config.refresh();
try {
Context.fromJAAS("client");
throw new Exception("What?");
} catch (LoginException le) {
// This is OK
}
}
UserGroupInformation getUgi() {
getLogger().trace("getting UGI instance");
if (kerberosUserReference.get() != null) {
// if there's a KerberosUser associated with this UGI, check the TGT and relogin if it is close to expiring
KerberosUser kerberosUser = kerberosUserReference.get();
getLogger().debug("kerberosUser is " + kerberosUser);
try {
getLogger().debug("checking TGT on kerberosUser [{}]", new Object[] {kerberosUser});
kerberosUser.checkTGTAndRelogin();
} catch (LoginException e) {
throw new ProcessException("Unable to relogin with kerberos credentials for " + kerberosUser.getPrincipal(), e);
}
} else {
getLogger().debug("kerberosUser was null, will not refresh TGT with KerberosUser");
}
return ugi;
}
@Override
public boolean commit() throws LoginException {
LCTest.logAction("commit");
if (succeeded == false) {
return false;
}
userPrincipal = new UnixPrincipal(username);
final Subject s = subject;
final UnixPrincipal up = userPrincipal;
java.security.AccessController.doPrivileged
((java.security.PrivilegedAction) () -> {
if (!s.getPrincipals().contains(up)) {
s.getPrincipals().add(up);
}
return null;
});
password = null;
commitSucceeded = true;
return true;
}
@Override
public String login(String username, String password) throws LoginException, SchedulerRestException {
try {
if ((username == null) || (password == null)) {
throw new LoginException("Empty login/password");
}
Session session = sessionStore.create(username);
session.connectToScheduler(new CredData(username, password));
logger.info("Binding user " + username + " to session " + session.getSessionId());
return session.getSessionId();
} catch (ActiveObjectCreationException | SchedulerException | NodeException e) {
throw new SchedulerRestException(e);
}
}
@Override
public boolean abort() throws LoginException {
LCTest.logAction("abort");
if (succeeded == false) {
return false;
}
clearState();
return true;
}
@Override
public boolean commit() throws LoginException {
if (this.userId != null) {
this.subject.getPrincipals().add(new UserPrincipal(this.userId));
return true;
}
return false;
}
public UUID login(final String realmName, final String username, final String password) throws LoginException {
final Realm realm = findRealm(realmName);
if (realm == null) {
throw new LoginException("No Tomcat realm available");
}
final Principal principal = realm.authenticate(username, password);
if (principal == null) {
throw new CredentialNotFoundException(username);
}
final Subject subject = createSubject(realm, principal);
return registerSubject(subject);
}
@Override
public boolean abort() throws LoginException
{
if (conn != null && conn.isOpen()) {
conn.close();
}
return super.abort();
}
@Override
public UserGroupInformation createAndLoginUser(Map<String, ?> properties) throws IOException {
final Configuration conf = new SecurityConfiguration();
UserGroupInformation.setConfiguration(conf);
try {
return UserGroupInformation.getCurrentUser();
} catch (final IOException e) {
logger.debug("Login failed.", e);
final Throwable cause = e.getCause();
if (cause instanceof LoginException) {
throw new SaslException("Failed to login.", cause);
}
throw new SaslException("Unexpected failure trying to login. ", cause);
}
}
@Override
public boolean commit() throws LoginException {
out.println("Commit of AbstractLoginModule is called");
out.println(name + ":commit:PASS");
return true;
}
/**
* Creates a CAS principal with attributes if the LDAP entry contains principal attributes.
*
* @param username Username that was successfully authenticated which is used for principal ID when
* {@link #setPrincipalIdAttribute(String)} is not specified.
* @param ldapEntry LDAP entry that may contain principal attributes.
*
* @return Principal if the LDAP entry contains at least a principal ID attribute value, null otherwise.
*
* @throws LoginException On security policy errors related to principal creation.
*/
protected Principal createPrincipal(final String username, final LdapEntry ldapEntry) throws LoginException {
final String id;
if (this.principalIdAttribute != null) {
final LdapAttribute principalAttr = ldapEntry.getAttribute(this.principalIdAttribute);
if (principalAttr == null || principalAttr.size() == 0) {
throw new LoginException(this.principalIdAttribute + " attribute not found for " + username);
}
if (principalAttr.size() > 1) {
if (this.allowMultiplePrincipalAttributeValues) {
logger.warn(
"Found multiple values for principal ID attribute: {}. Using first value={}.",
principalAttr,
principalAttr.getStringValue());
} else {
throw new LoginException("Multiple principal values not allowed: " + principalAttr);
}
}
id = principalAttr.getStringValue();
} else {
id = username;
}
final Map<String, Object> attributeMap = new LinkedHashMap<String, Object>(this.principalAttributeMap.size());
for (String ldapAttrName : this.principalAttributeMap.keySet()) {
final LdapAttribute attr = ldapEntry.getAttribute(ldapAttrName);
if (attr != null) {
logger.debug("Found principal attribute: {}", attr);
final String principalAttrName = this.principalAttributeMap.get(ldapAttrName);
if (attr.size() > 1) {
attributeMap.put(principalAttrName, attr.getStringValues());
} else {
attributeMap.put(principalAttrName, attr.getStringValue());
}
}
}
return new SimplePrincipal(id, attributeMap);
}
@Override
public Set<String> resolve(org.taktik.icure.dto.filter.service.ServiceByHcPartyTagCodeDateFilter filter, Filters context) {
try {
String hcPartyId = filter.getHealthcarePartyId() != null ? filter.getHealthcarePartyId() : getLoggedHealthCarePartyId();
HashSet<String> ids = null;
String patientSFK = filter.getPatientSecretForeignKey();
List<String> patientSFKList = patientSFK != null ? Arrays.asList(patientSFK) : null;
if (filter.getTagType() != null && filter.getTagCode() != null) {
ids = new HashSet<>(contactLogic.listServiceIdsByTag(
hcPartyId,
patientSFKList, filter.getTagType(),
filter.getTagCode(), filter.getStartValueDate(), filter.getEndValueDate()
));
}
if (filter.getCodeType() != null && filter.getCodeCode() != null) {
List<String> byCode = contactLogic.listServiceIdsByCode(
hcPartyId,
patientSFKList, filter.getCodeType(),
filter.getCodeCode(), filter.getStartValueDate(), filter.getEndValueDate()
);
if (ids==null) { ids = new HashSet<>(byCode); } else { ids.retainAll(byCode); }
}
return ids != null ? ids : new HashSet<>();
} catch (LoginException e) {
throw new IllegalArgumentException(e);
}
}
/**
* Log out this user.
*
* @return <code>true</code> in all cases because the
* <code>LoginModule</code> should not be ignored
*
* @exception LoginException if logging out failed
*/
@Override
public boolean logout() throws LoginException {
subject.getPrincipals().remove(principal);
committed = false;
principal = null;
return (true);
}
public LoginContext getLoginContextFromKeytab( String principal, String keytab ) throws LoginException {
Map<String, String> keytabConfig = new HashMap<String, String>( LOGIN_CONFIG_OPTS_KERBEROS_KEYTAB );
keytabConfig.put( "keyTab", keytab );
keytabConfig.put( "principal", principal );
// Create the configuration and from them, a new login context
AppConfigurationEntry config =
new AppConfigurationEntry( Krb5LoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, keytabConfig );
AppConfigurationEntry[] configEntries = new AppConfigurationEntry[] { config };
Subject subject = new Subject();
return new LoginContext( KERBEROS_APP_NAME, subject, null, new PentahoLoginConfiguration( configEntries ) );
}
public static void main(String[] args) throws Exception {
new OneKDC(null).writeJAASConf();
// KDC would save ccache for client
System.setProperty("test.kdc.save.ccache", "cache.here");
try (FileOutputStream fos = new FileOutputStream(OneKDC.JAAS_CONF)) {
fos.write((
"me {\n" +
" com.sun.security.auth.module.Krb5LoginModule required\n" +
" principal=\"" + OneKDC.USER + "\"\n" +
" useTicketCache=true\n" +
" ticketCache=cache.here\n" +
" isInitiator=true\n" +
" storeKey=true;\n};\n"
).getBytes());
}
// The first login will use default callback and succeed
Context.fromJAAS("me");
// The second login uses ccache and won't be able to store the keys
try {
Context.fromJAAS("me");
throw new Exception("Should fail");
} catch (LoginException le) {
if (le.getMessage().indexOf("NullPointerException") >= 0
|| le.getCause() instanceof NullPointerException) {
throw new Exception("NPE");
}
}
}
/**
* Overriding to allow for role discovery based on text files.
*
* @param username The name of the user being examined. This is the same
* name returned by getUserNameForCertificates.
* @return A Set of name Strings for roles this user belongs to.
* @throws LoginException Thrown if unable to find role definition file.
*/
@Override
protected Set<String> getUserRoles(String username) throws LoginException {
Set<String> userRoles = rolesByUser.get(username);
if (userRoles == null) {
userRoles = Collections.emptySet();
}
return userRoles;
}
@ApiOperation(
value = "Get ids of patients matching the provided filter for the current user (HcParty) ",
response = String.class,
responseContainer = "Array",
httpMethod = "POST"
)
@POST
@Path("/match")
public List<String> matchBy(Filter filter) throws LoginException {
return new ArrayList<>(filters.resolve(filter));
}
/**
* Retrieves the caller's Subject, or Subject obtained by logging in
* via the specified caller.
*
* Caller must have permission to:
* - access the Subject
* - create LoginContext
* - read the auth.login.defaultCallbackHandler security property
*
* NOTE: This method is used by JSSE Kerberos Cipher Suites
*/
public static Subject getSubject(GSSCaller caller,
AccessControlContext acc) throws LoginException {
// Try to get the Subject from acc
Subject subject = Subject.getSubject(acc);
// Try to get Subject obtained from GSSUtil
if (subject == null && !GSSUtil.useSubjectCredsOnly(caller)) {
subject = GSSUtil.login(caller, GSSUtil.GSS_KRB5_MECH_OID);
}
return subject;
}
/**
* Returns true if user was successfully authenticated against Kerberos
*
* @param username username without Kerberos realm attached or with correct realm attached
* @param password kerberos password
* @return true if user was successfully authenticated
*/
public boolean validUser(String username, String password) {
try {
authenticateSubject(username, password);
logoutSubject();
return true;
} catch (LoginException le) {
checkKerberosServerAvailable(le);
logger.debug("Failed to authenticate user " + username, le);
return false;
}
}
public static void go(String... expected)
throws Exception {
try {
go0(expected);
} catch (BindException be) {
System.out.println("The random port is used by another process");
} catch (LoginException le) {
Throwable cause = le.getCause();
if (cause instanceof Asn1Exception) {
System.out.println("Bad packet possibly from another process");
return;
}
throw le;
}
}
private Subject loginServer() throws SaslException, PrivilegedActionException, LoginException {
AppConfigurationEntry[] entries = Configuration.getConfiguration().getAppConfigurationEntry(JASS_SERVER_SECTION);
if (entries == null) {
return null;
}
LoginContext loginContext = new LoginContext(JASS_SERVER_SECTION, new ClientCallbackHandler(null));
loginContext.login();
return loginContext.getSubject();
}
@Override
public boolean abort() throws LoginException {
LCTest.logAction("abort");
if (succeeded == false) {
return false;
}
clearState();
return true;
}
public static void main(String[] args) throws LoginException {
System.setProperty("java.security.auth.login.config",
System.getProperty("test.src")
+ System.getProperty("file.separator")
+ "shared.config");
new LoginContext("SharedState").login();
}
private void checkAlias() throws LoginException {
if (keyStoreAlias == null) {
throw new LoginException
("Need to specify an alias option to use " +
"KeyStoreLoginModule non-interactively.");
}
}
@Override
public boolean commit() throws LoginException
{
if (conn != null && conn.isOpen()) {
conn.close();
}
return super.commit();
}