下面列出了org.hamcrest.BaseMatcher#javax.security.auth.login.Configuration 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Inject
public AuthenticationServlet(AccountStore accountStore,
Configuration configuration,
SessionManager sessionManager,
@Named(CoreSettingsNames.WAVE_SERVER_DOMAIN) String domain,
Config config
/* ,WelcomeRobot welcomeBot */) {
Preconditions.checkNotNull(accountStore, "AccountStore is null");
Preconditions.checkNotNull(configuration, "Configuration is null");
Preconditions.checkNotNull(sessionManager, "Session manager is null");
this.accountStore = accountStore;
this.configuration = configuration;
this.sessionManager = sessionManager;
this.domain = domain.toLowerCase();
this.isClientAuthEnabled = config.getBoolean("security.enable_clientauth");
this.clientAuthCertDomain = config.getString("security.clientauth_cert_domain").toLowerCase();
this.isRegistrationDisabled = config.getBoolean("administration.disable_registration");
this.isLoginPageDisabled = config.getBoolean("administration.disable_loginpage");
// this.welcomeBot = welcomeBot;
this.analyticsAccount = config.getString("administration.analytics_account");
}
/**
* A new instance of LoginConfigImpl must be created for each login request
* since it's only used by a single (caller, mech) pair
* @param caller defined in GSSUtil as CALLER_XXX final fields
* @param oid defined in GSSUtil as XXX_MECH_OID final fields
*/
public LoginConfigImpl(GSSCaller caller, Oid mech) {
this.caller = caller;
if (mech.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
mechName = "krb5";
} else {
throw new IllegalArgumentException(mech.toString() + " not supported");
}
config = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction <Configuration> () {
public Configuration run() {
return Configuration.getConfiguration();
}
});
}
public SaslServerCallbackHandler(Configuration configuration) throws IOException {
AppConfigurationEntry configurationEntries[] = configuration.getAppConfigurationEntry(SERVER_JAAS_SECTION);
if (configurationEntries == null) {
String errorMessage = "Could not find a '" + SERVER_JAAS_SECTION + "' entry in this configuration: Server cannot start.";
throw new IOException(errorMessage);
}
credentials.clear();
for (AppConfigurationEntry entry : configurationEntries) {
Map<String, ?> options = entry.getOptions();
// Populate DIGEST-MD5 user -> password map with JAAS configuration entries from the "Server" section.
// Usernames are distinguished from other options by prefixing the username with a "user_" prefix.
for (Map.Entry<String, ?> pair : options.entrySet()) {
String key = pair.getKey();
if (key.startsWith(USER_PREFIX)) {
String userName = key.substring(USER_PREFIX.length());
credentials.put(userName, (String) pair.getValue());
}
}
}
}
public static Subject getKerberosSubject() {
Subject subject = null;
try {
Configuration jaasConf = getKerberosJAASConfiguration();
if (jaasConf != null) {
log.attemptingKerberosLogin(getKerberosLoginConfigLocation());
LoginContext lc = new LoginContext(JGSS_LOGIN_MODULE, null, null, jaasConf);
lc.login();
subject = lc.getSubject();
}
} catch (Exception e) {
log.failedKerberosLogin(getKerberosLoginConfigLocation(), JGSS_LOGIN_MODULE, e);
}
return subject;
}
public SaslServerCallbackHandler(Configuration configuration) throws IOException {
AppConfigurationEntry[] configurationEntries = configuration.getAppConfigurationEntry(JASS_SERVER_SECTION);
if (configurationEntries == null) {
String errorMessage = "Could not find a '" + JASS_SERVER_SECTION + "' entry in this configuration: Server cannot start.";
throw new IOException(errorMessage);
}
credentials.clear();
for (AppConfigurationEntry entry : configurationEntries) {
Map<String, ?> options = entry.getOptions();
// Populate DIGEST-MD5 user -> password map with JAAS configuration entries from the "Server" section.
// Usernames are distinguished from other options by prefixing the username with a "user_" prefix.
for (Map.Entry<String, ?> pair : options.entrySet()) {
String key = pair.getKey();
if (key.startsWith(USER_PREFIX)) {
String userName = key.substring(USER_PREFIX.length());
credentials.put(userName, (String) pair.getValue());
}
}
}
}
public static void testLogin(String confName, char[] passwd,
Configuration cf, boolean expectException) {
try {
CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
LoginContext lc = new LoginContext(confName, new Subject(),
ch, cf);
lc.login();
if (expectException) {
throw new RuntimeException("Login Test failed: "
+ "expected LoginException not thrown");
}
} catch (LoginException le) {
if (!expectException) {
System.out.println("Login Test failed: "
+ "received Unexpected exception.");
throw new RuntimeException(le);
}
}
}
public static void testLogin(String confName, char[] passwd,
Configuration cf, boolean expectException) {
try {
CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
LoginContext lc = new LoginContext(confName, new Subject(),
ch, cf);
lc.login();
if (expectException) {
throw new RuntimeException("Login Test failed: "
+ "expected LoginException not thrown");
}
} catch (LoginException le) {
if (!expectException) {
System.out.println("Login Test failed: "
+ "received Unexpected exception.");
throw new RuntimeException(le);
}
}
}
/**
* A new instance of LoginConfigImpl must be created for each login request
* since it's only used by a single (caller, mech) pair
* @param caller defined in GSSUtil as CALLER_XXX final fields
* @param oid defined in GSSUtil as XXX_MECH_OID final fields
*/
public LoginConfigImpl(GSSCaller caller, Oid mech) {
this.caller = caller;
if (mech.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
mechName = "krb5";
} else {
throw new IllegalArgumentException(mech.toString() + " not supported");
}
config = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction <Configuration> () {
public Configuration run() {
return Configuration.getConfiguration();
}
});
}
public static void testLogin(String confName, char[] passwd,
Configuration cf, boolean expectException) {
try {
CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
LoginContext lc = new LoginContext(confName, new Subject(),
ch, cf);
lc.login();
if (expectException) {
throw new RuntimeException("Login Test failed: "
+ "expected LoginException not thrown");
}
} catch (LoginException le) {
if (!expectException) {
System.out.println("Login Test failed: "
+ "received Unexpected exception.");
throw new RuntimeException(le);
}
}
}
private String setJaasConfiguration(Properties config) throws Exception {
String keytabFile = config.getProperty(ZOOKEEPER_KERBEROS_KEYTAB).trim();
if (keytabFile == null || keytabFile.length() == 0) {
throw new IllegalArgumentException(ZOOKEEPER_KERBEROS_KEYTAB
+ " must be specified");
}
String principal = config.getProperty(ZOOKEEPER_KERBEROS_PRINCIPAL)
.trim();
if (principal == null || principal.length() == 0) {
throw new IllegalArgumentException(ZOOKEEPER_KERBEROS_PRINCIPAL
+ " must be specified");
}
// This is equivalent to writing a jaas.conf file and setting the system
// property, "java.security.auth.login.config", to point to it
JaasConfiguration jConf =
new JaasConfiguration(JAAS_LOGIN_ENTRY_NAME, principal, keytabFile);
Configuration.setConfiguration(jConf);
return principal.split("[/@]")[0];
}
/**
* Construct a JAAS configuration object per storm configuration file
*
* @param storm_conf Storm configuration
* @return JAAS configuration object
*/
public static Configuration GetConfiguration(Map storm_conf) {
Configuration login_conf = null;
// find login file configuration from Storm configuration
String loginConfigurationFile = (String) storm_conf.get("java.security.auth.login.config");
if ((loginConfigurationFile != null) && (loginConfigurationFile.length() > 0)) {
File config_file = new File(loginConfigurationFile);
if (!config_file.canRead()) {
throw new RuntimeException("File " + loginConfigurationFile + " cannot be read.");
}
try {
URI config_uri = config_file.toURI();
login_conf = Configuration.getInstance("JavaLoginConfig", new URIParameter(config_uri));
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
return login_conf;
}
public static void testLogin(String confName, char[] passwd,
Configuration cf, boolean expectException) {
try {
CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
LoginContext lc = new LoginContext(confName, new Subject(),
ch, cf);
lc.login();
if (expectException) {
throw new RuntimeException("Login Test failed: "
+ "expected LoginException not thrown");
}
} catch (LoginException le) {
if (!expectException) {
System.out.println("Login Test failed: "
+ "received Unexpected exception.");
throw new RuntimeException(le);
}
}
}
public static void testLogin(String confName, char[] passwd,
Configuration cf, boolean expectException) {
try {
CallbackHandler ch = new MyCallbackHandler("testUser", passwd);
LoginContext lc = new LoginContext(confName, new Subject(),
ch, cf);
lc.login();
if (expectException) {
throw new RuntimeException("Login Test failed: "
+ "expected LoginException not thrown");
}
} catch (LoginException le) {
if (!expectException) {
System.out.println("Login Test failed: "
+ "received Unexpected exception.");
throw new RuntimeException(le);
}
}
}
private static Configuration createJaasConfiguration() {
return new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
if (!"KDC".equals(name)) {
throw new IllegalArgumentException("Unexpected name '" + name + "'");
}
AppConfigurationEntry[] entries = new AppConfigurationEntry[1];
Map<String, Object> options = new HashMap<>();
options.put("debug", config.getDebug());
options.put("refreshKrb5Config", "true");
options.put("storeKey", "true");
if("true".equalsIgnoreCase(config.getUseKeyTab())) {
options.put("useKeyTab", config.getUseKeyTab());
options.put("keyTab", config.getKeyTab());
options.put("principal", config.getPrincipal());
}
options.put("isInitiator", "true");
entries[0] = new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", REQUIRED, options);
return entries;
}
};
}
private Configuration createJaasConfigurationForDirectGrant(String scope) {
return new Configuration() {
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, Object> options = new HashMap<>();
options.put(AbstractKeycloakLoginModule.KEYCLOAK_CONFIG_FILE_OPTION, DIRECT_GRANT_CONFIG_FILE.getAbsolutePath());
if (scope != null) {
options.put(DirectAccessGrantsLoginModule.SCOPE_OPTION, scope);
}
AppConfigurationEntry LMConfiguration = new AppConfigurationEntry(DirectAccessGrantsLoginModule.class.getName(), AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options);
return new AppConfigurationEntry[] { LMConfiguration };
}
};
}
/**
* A new instance of LoginConfigImpl must be created for each login request
* since it's only used by a single (caller, mech) pair
* @param caller defined in GSSUtil as CALLER_XXX final fields
* @param mech defined in GSSUtil as XXX_MECH_OID final fields
*/
public LoginConfigImpl(GSSCaller caller, Oid mech) {
this.caller = caller;
if (mech.equals(GSSUtil.GSS_KRB5_MECH_OID)) {
mechName = "krb5";
} else {
throw new IllegalArgumentException(mech.toString() + " not supported");
}
config = java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction <Configuration> () {
public Configuration run() {
return Configuration.getConfiguration();
}
});
}
private int testStringProvider(int testnum) throws Exception {
// get an instance of JavaLoginConfig from SUN
Configuration c = Configuration.getInstance(JAVA_CONFIG, null, "SUN");
doTest(c, testnum++);
// get an instance of JavaLoginConfig from SunRsaSign
try {
c = Configuration.getInstance(JAVA_CONFIG, null, "SunRsaSign");
throw new SecurityException("test " + testnum++ + " failed");
} catch (NoSuchAlgorithmException nsae) {
// good
System.out.println("test " + testnum++ + " passed");
}
// get an instance of JavaLoginConfig from FOO
try {
c = Configuration.getInstance(JAVA_CONFIG, null, "FOO");
throw new SecurityException("test " + testnum++ + " failed");
} catch (NoSuchProviderException nspe) {
// good
System.out.println("test " + testnum++ + " passed");
}
return testnum;
}
private int testProvider(int testnum) throws Exception {
// get an instance of JavaLoginConfig from SUN
Configuration c = Configuration.getInstance(JAVA_CONFIG,
null,
Security.getProvider("SUN"));
doTest(c, testnum++);
// get an instance of JavaLoginConfig from SunRsaSign
try {
c = Configuration.getInstance(JAVA_CONFIG,
null,
Security.getProvider("SunRsaSign"));
throw new SecurityException("test " + testnum++ + " failed");
} catch (NoSuchAlgorithmException nsae) {
// good
System.out.println("test " + testnum++ + " passed");
}
return testnum;
}
@BeforeClass
public static void beforeClass() throws Exception {
testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
Assert.assertTrue(testDir.mkdirs());
File kdcDir = new File(testDir, KDC);
Assert.assertTrue(kdcDir.mkdirs());
keytabFile = new File(testDir, TEST_KEYTAB);
jaasConfigFile = new File(testDir, KAFKA_JAAS_CONF);
jaasConfigFile.createNewFile();
jaasConfigFile.setReadable(true);
String jaasConf = JAAS_CONF.replaceAll("keyTabFile", keytabFile.getAbsolutePath());
FileOutputStream outputStream = new FileOutputStream(jaasConfigFile);
IOUtils.write(jaasConf, outputStream);
outputStream.close();
plainTextPort = NetworkUtils.getRandomPort();
securePort = NetworkUtils.getRandomPort();
// reload configuration when getConfiguration is called next
Configuration.setConfiguration(null);
System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, jaasConfigFile.getAbsolutePath());
SecureKafkaBase.beforeClass();
}
/**
* Constructor based on a JAAS configuration
*
* For digest, you should have a pair of user name and password defined.
*
* @param configuration
* @throws IOException
*/
public ClientCallbackHandler(Configuration configuration) throws IOException {
if (configuration == null)
return;
AppConfigurationEntry configurationEntries[] = configuration.getAppConfigurationEntry(AuthUtils.LOGIN_CONTEXT_CLIENT);
if (configurationEntries == null) {
String errorMessage = "Could not find a '" + AuthUtils.LOGIN_CONTEXT_CLIENT + "' entry in this configuration: Client cannot start.";
throw new IOException(errorMessage);
}
_password = "";
for (AppConfigurationEntry entry : configurationEntries) {
if (entry.getOptions().get(USERNAME) != null) {
_username = (String) entry.getOptions().get(USERNAME);
}
if (entry.getOptions().get(PASSWORD) != null) {
_password = (String) entry.getOptions().get(PASSWORD);
}
}
}
private void doCustomTest(Configuration c,
int testnum,
Provider custom) throws Exception {
testnum = doCommon(c, testnum);
// test getProvider
if (custom == c.getProvider() &&
"GetInstanceProvider".equals(c.getProvider().getName())) {
System.out.println("test " + testnum + " (getProvider) passed");
} else {
throw new SecurityException
("test " + testnum + " (getProvider) failed");
}
// test getType
if ("GetInstanceConfigSpi".equals(c.getType())) {
System.out.println("test " + testnum + "(getType) passed");
} else {
throw new SecurityException("test " + testnum +
" (getType) failed");
}
}
private void doTest(Configuration c, int testnum) throws Exception {
testnum = doCommon(c, testnum);
// test getProvider
if ("SUN".equals(c.getProvider().getName())) {
System.out.println("test " + testnum + " (getProvider) passed");
} else {
throw new SecurityException("test " + testnum +
" (getProvider) failed");
}
// test getType
if (JAVA_CONFIG.equals(c.getType())) {
System.out.println("test " + testnum + " (getType) passed");
} else {
throw new SecurityException("test " + testnum +
" (getType) failed");
}
}
public static Subject loginUsingTicketCache(final String principal, final Path cachePath) throws LoginException {
final Set<Principal> principals = new HashSet<Principal>();
principals.add(new KerberosPrincipal(principal));
final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
final Configuration conf = useTicketCache(principal, cachePath);
final String confName = "TicketCacheConf";
final LoginContext loginContext = new LoginContext(confName, subject, null, conf);
loginContext.login();
return loginContext.getSubject();
}
private static Configuration createConfiguration(String principal, String keytabLocation)
{
ImmutableMap.Builder<String, String> optionsBuilder = ImmutableMap.<String, String>builder()
.put("useKeyTab", "true")
.put("storeKey", "true")
.put("doNotPrompt", "true")
.put("isInitiator", "true")
.put("principal", principal)
.put("keyTab", keytabLocation);
if (log.isDebugEnabled()) {
optionsBuilder.put("debug", "true");
}
Map<String, String> options = optionsBuilder.build();
return new Configuration()
{
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name)
{
return new AppConfigurationEntry[] {
new AppConfigurationEntry(
KERBEROS_LOGIN_MODULE,
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
options)};
}
};
}
public static Subject loginUsingKeytab(final String principal, final Path keytabPath, final boolean initiator) throws LoginException {
final Set<Principal> principals = new HashSet<Principal>();
principals.add(new KerberosPrincipal(principal));
final Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
final Configuration conf = useKeytab(principal, keytabPath, initiator);
final String confName = "KeytabConf";
final LoginContext loginContext = new LoginContext(confName, subject, null, conf);
loginContext.login();
return loginContext.getSubject();
}
@Before
public void setUp() throws Exception {
tempDir = Files.createTempDir();
passwordFile = new File(tempDir, "password-file");
jaasConfigFile = new File(tempDir, "jaas_config.file");
writePasswordFile(passwordFile);
writeJaasFile(jaasConfigFile, passwordFile);
Configuration.setConfiguration(null);
System.setProperty("java.security.auth.login.config", jaasConfigFile.getAbsolutePath());
super.setUp();
}
public static void init(org.apache.commons.configuration.Configuration atlasConfiguration) throws AtlasException {
LOG.debug("==> InMemoryJAASConfiguration.init()");
if (atlasConfiguration != null && !atlasConfiguration.isEmpty()) {
Properties properties = ConfigurationConverter.getProperties(atlasConfiguration);
init(properties);
} else {
throw new AtlasException("Failed to load JAAS application properties: configuration NULL or empty!");
}
LOG.debug("<== InMemoryJAASConfiguration.init()");
}
private RemoteConfigurationRegistryJAASConfig(List<RemoteConfigurationRegistryConfig> configs, AliasService aliasService) {
try {
delegate = Configuration.getConfiguration();
} catch(Exception e) {
//populate the original error with a meaningful message; logging will happen later in the call hierarchy
final String message = String.format(Locale.ROOT, "%s: %s", JAAS_CONFIG_ERRROR_PREFIX, System.getProperty(GatewayConfig.KRB5_LOGIN_CONFIG, "Undefined"));
throw new ConfigurationException(message, e);
}
validateKeytabFile();
this.aliasService = aliasService;
// Populate context entries
for (RemoteConfigurationRegistryConfig config : configs) {
if (config.isSecureRegistry()) {
contextEntries.put(config.getName(), createEntries(config));
}
}
// If there is at least one context entry, then set this as the client configuration
if (!contextEntries.isEmpty()) {
// TODO: PJZ: ZooKeeper 3.6.0 will have per-client JAAS Configuration support; Upgrade ASAP!!
// For now, set this as the static JAAS configuration
Configuration.setConfiguration(this);
}
}
@Override
protected void configure() {
bind(WaveServerImpl.class).in(Singleton.class);
// Receive updates from the outside world, and push them into our local Wave
// Server.
bind(WaveletFederationListener.Factory.class).annotatedWith(FederationRemoteBridge.class).to(
WaveServerImpl.class);
// Provide history and respond to submits about our own local waves.
bind(WaveletFederationProvider.class).annotatedWith(FederationHostBridge.class).to(
WaveServerImpl.class);
install(waveServerModule);
TypeLiteral<List<String>> certs = new TypeLiteral<List<String>>() {};
bind(certs).annotatedWith(Names.named("certs")).toInstance(Arrays.<String> asList());
bind(ProtoSerializer.class).in(Singleton.class);
bind(Configuration.class).toInstance(Configuration.getConfiguration());
bind(SessionManager.class).to(SessionManagerImpl.class).in(Singleton.class);
bind(ServerRpcProvider.class).in(Singleton.class);
// bind(RobotRegistrar.class).to(RobotRegistrarImpl.class);
requestStaticInjection(WebSocketChannel.class);
}
public static void main(String... args) {
String rightConfigName = "PT";
String wrongConfigName = "NT";
char[] rightPwd = new char[]{'t', 'e', 's', 't', 'P', 'a', 's', 's',
'w', 'o', 'r', 'd', '1'};
char[] wrongPwd = new char[]{'w', 'r', 'o', 'n', 'g', 'P', 'a', 's',
's','w', 'o', 'r', 'd'};
// Test with wrong configuration name
// Expect LoginException when initiate a new LoginContext object
testConfigName(wrongConfigName, true);
System.out.println("Wrong Config Name Test passed ");
// Spedify two loginModules: SmartLoginModule and DummyLoginModule
// Flags: required-required
// Test with right password for SmartLoginModule
// No exception is expected
Configuration cf = new MyConfiguration();
testLogin(rightConfigName, rightPwd, cf, false);
System.out.println("Positive test passed");
// Spedify two loginModules: SmartLoginModule and DummyLoginModule
// Flags: required-required
// Test with wrong password for SmartLoginModule
// Expect LoginException by calling LoginContext.login() method
testLogin(rightConfigName, wrongPwd, cf, true);
System.out.println("Should fail test passed");
// Spedify two loginModules: SmartLoginModule and DummyLoginModule
// Change the flags from required-required to optional-sufficient
// Test with wrong password for SmartLoginModule, while DummyLoginModule
// always passes
// No Exception is expected
cf = new MyConfiguration(true);
testLogin(rightConfigName, wrongPwd, cf, false);
System.out.println("One module fails where are other module succeeeds "
+ "Test passed with optional-sufficient flags");
}