Java Code Examples for javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag#REQUIRED

The following examples show how to use javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag#REQUIRED . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JAASServer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private JAASLoginInterceptor createTestJaasLoginInterceptor() {
    JAASLoginInterceptor jaasInt = new JAASLoginInterceptor();
    jaasInt.setReportFault(true);
    Configuration config = new Configuration() {

        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> options = new HashMap<>();
            AppConfigurationEntry configEntry = new AppConfigurationEntry(
                                                                          TestUserPasswordLoginModule.class
                                                                              .getName(),
                                                                          LoginModuleControlFlag.REQUIRED,
                                                                          options);
            return Collections.singleton(configEntry).toArray(new AppConfigurationEntry[] {});
        }
    };
    jaasInt.setLoginConfig(config);
    return jaasInt;
}
 
Example 2
Source File: AuthTestUtil.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
public static Configuration makeConfiguration() {
  return new Configuration() {
    @Override
    public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
      if (name.equals("Wave")) {
        AppConfigurationEntry entry =
            new AppConfigurationEntry(AccountStoreLoginModule.class.getName(),
                LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>());

        return new AppConfigurationEntry[] {entry};
      } else {
        return null;
      }
    }
  };
}
 
Example 3
Source File: AuthTestUtil.java    From swellrt with Apache License 2.0 6 votes vote down vote up
public static Configuration makeConfiguration() {
  return new Configuration() {
    @Override
    public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
      if (name.equals("Wave")) {
        AppConfigurationEntry entry =
            new AppConfigurationEntry(AccountStoreLoginModule.class.getName(),
                LoginModuleControlFlag.REQUIRED, new HashMap<String, Object>());

        return new AppConfigurationEntry[] {entry};
      } else {
        return null;
      }
    }
  };
}
 
Example 4
Source File: KerberosUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public LoginContext getLoginContextFromUsernamePassword( final String principal, final String password ) throws LoginException {
  Map<String, String> opts = new HashMap<String, String>( LOGIN_CONFIG_OPTS_KERBEROS_USER );
  opts.put( "principal", principal );
  AppConfigurationEntry[] appConfigurationEntries =
      new AppConfigurationEntry[] { new AppConfigurationEntry( Krb5LoginModule.class.getName(),
          LoginModuleControlFlag.REQUIRED, opts ) };
  return new LoginContext( KERBEROS_APP_NAME, new Subject(), new CallbackHandler() {

    @Override
    public void handle( Callback[] callbacks ) throws IOException, UnsupportedCallbackException {
      for ( Callback callback : callbacks ) {
        if ( callback instanceof NameCallback ) {
          ( (NameCallback) callback ).setName( principal );
        } else if ( callback instanceof PasswordCallback ) {
          ( (PasswordCallback) callback ).setPassword( password.toCharArray() );
        } else {
          throw new UnsupportedCallbackException( callback );
        }
      }
    }
  }, new PentahoLoginConfiguration( appConfigurationEntries ) );
}
 
Example 5
Source File: JaasConfiguration.java    From registry with Apache License 2.0 6 votes vote down vote up
private LoginModuleControlFlag loginModuleControlFlag(String flag) {
    LoginModuleControlFlag controlFlag;
    switch (flag.toUpperCase(Locale.ROOT)) {
        case "REQUIRED":
            controlFlag = LoginModuleControlFlag.REQUIRED;
            break;
        case "REQUISITE":
            controlFlag = LoginModuleControlFlag.REQUISITE;
            break;
        case "SUFFICIENT":
            controlFlag = LoginModuleControlFlag.SUFFICIENT;
            break;
        case "OPTIONAL":
            controlFlag = LoginModuleControlFlag.OPTIONAL;
            break;
        default:
            throw new IllegalArgumentException("Invalid login module control flag '" + flag + "' in JAAS config");
    }
    return controlFlag;
}
 
Example 6
Source File: AuthenticationConfigParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private AppConfigurationEntry getEntry(XMLEventReader xmlEventReader) throws XMLStreamException
{
   XMLEvent xmlEvent = xmlEventReader.nextEvent();
   Map<String, Object> options = new HashMap<String,Object>();
   
   String codeName = null;
   LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;
   
   //We got the login-module element
   StartElement loginModuleElement = (StartElement) xmlEvent;
   //We got the login-module element
   Iterator<Attribute> attrs = loginModuleElement.getAttributes();
   while(attrs.hasNext())
   {
      Attribute attribute = attrs.next();
      
      QName attQName = attribute.getName();
      String attributeValue = StaxParserUtil.getAttributeValue(attribute);
      
      if("code".equals(attQName.getLocalPart()))
      {
         codeName = attributeValue;
      }
      else if("flag".equals(attQName.getLocalPart()))
      {
         controlFlag = getControlFlag(attributeValue);
      } 
   } 
   //See if there are options
   ModuleOptionParser moParser = new ModuleOptionParser();
   options.putAll(moParser.parse(xmlEventReader));
   
   return new AppConfigurationEntry(codeName, controlFlag, options); 
}
 
Example 7
Source File: AuthenticationConfigParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private LoginModuleControlFlag getControlFlag(String flag)
{
   if("required".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.REQUIRED;
   if("sufficient".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.SUFFICIENT;
   if("optional".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.OPTIONAL;
   if("requisite".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.REQUISITE;

   throw PicketBoxMessages.MESSAGES.invalidControlFlag(flag);
}
 
Example 8
Source File: PicketBoxProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private AppConfigurationEntry.LoginModuleControlFlag getFlag(String flag)
{
   if("REQUIRED".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.REQUIRED;
   if("REQUISITE".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.REQUISITE;
   if("SUFFICIENT".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.SUFFICIENT;
   return LoginModuleControlFlag.OPTIONAL;
}
 
Example 9
Source File: LoginContextBuilder.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
private LoginContext getClientLoginContext() throws LoginException {
    Configuration config = new Configuration() {
        @Override
        public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
            Map<String, String> options = new HashMap<String, String>();
            options.put("multi-threaded", "true");
            options.put("restore-login-identity", "true");

            AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);
            return new AppConfigurationEntry[] { clmEntry };
        }
    };
    return getLoginContext(config);
}
 
Example 10
Source File: KerberosAuth.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name)
{
  if (name.equals(com.datatorrent.stram.security.KerberosAuth.class.getName())) {
    AppConfigurationEntry[] configEntries = new AppConfigurationEntry[1];
    HashMap<String, String> params = new HashMap<>();
    params.put("useTicketCache", "true");
    params.put("principal", principal);
    configEntries[0] = new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
        LoginModuleControlFlag.REQUIRED, params);
    return configEntries;
  } else {
    return null;
  }
}
 
Example 11
Source File: StaticJAASConfiguration.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * {@inheritDoc}
 *
 * @see javax.security.auth.login.Configuration#getAppConfigurationEntry(java.lang.String)
 */
@Override
public AppConfigurationEntry[] getAppConfigurationEntry ( String name ) {
    return new AppConfigurationEntry[] {
        new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", LoginModuleControlFlag.REQUIRED, this.options)
    };
}
 
Example 12
Source File: AuthenticationJASPIConfigParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private LoginModuleControlFlag getControlFlag(String flag)
{
   if ("required".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.REQUIRED;
   if ("sufficient".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.SUFFICIENT;
   if ("optional".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.OPTIONAL;
   if ("requisite".equalsIgnoreCase(flag))
      return LoginModuleControlFlag.REQUISITE;
   throw PicketBoxMessages.MESSAGES.invalidControlFlag(flag);
}
 
Example 13
Source File: LoginConfiguration.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void init() {
	Debug.info("Configuring authentication service ...");
	String m = ApplicationProperty.AuthenticationModules.value();
	String[] modules = (m == null || m.isEmpty() ? new String[] {} : m.split(";"));
	sEntries = new AppConfigurationEntry[modules.length];
	for (int idx = 0; idx < modules.length; idx++) {
		HashMap<String, Object> options = new HashMap<String, Object>();
		String[] module = modules[idx].split(" ");
		LoginModuleControlFlag flag = LoginModuleControlFlag.SUFFICIENT;
		String name = module[module.length == 1 ? 0 : 1];
		if (module.length > 1) {
			String f = module[0];
			if (f.equalsIgnoreCase("sufficient")) flag = LoginModuleControlFlag.SUFFICIENT;
			else if (f.equalsIgnoreCase("optional")) flag = LoginModuleControlFlag.OPTIONAL;
			else if (f.equalsIgnoreCase("required")) flag = LoginModuleControlFlag.REQUIRED;
			else if (f.equalsIgnoreCase("requisite")) flag = LoginModuleControlFlag.REQUISITE;
		}
		if (module.length > 2)
			for (int i = 2; i < module.length; i++) {
				String[] option = module[i].split("=");
				if (option.length == 1)
					options.put(option[0], "true");
				else
					options.put(option[0], option[1]);
			}
		Debug.info("  Using " + flag + " " + name + " " + options);
		sEntries[idx] = new AppConfigurationEntry(name, flag, options);
	}
}
 
Example 14
Source File: AuthenticationJASPIConfigParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private AppConfigurationEntry getJAASEntry(XMLEventReader xmlEventReader) throws XMLStreamException
{
   XMLEvent xmlEvent = xmlEventReader.nextEvent();
   Map<String, Object> options = new HashMap<String, Object>();

   String codeName = null;
   LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;

   //We got the login-module element
   StartElement loginModuleElement = (StartElement) xmlEvent;
   //We got the login-module element
   Iterator<Attribute> attrs = loginModuleElement.getAttributes();
   while (attrs.hasNext())
   {
      Attribute attribute = attrs.next();
      QName attQName = attribute.getName();
      String attributeValue = StaxParserUtil.getAttributeValue(attribute);

      if ("code".equals(attQName.getLocalPart()))
      {
         codeName = attributeValue;
      }
      else if ("flag".equals(attQName.getLocalPart()))
      {
         controlFlag = getControlFlag(attributeValue);
      }
   }
   //See if there are options
   ModuleOptionParser moParser = new ModuleOptionParser();
   options.putAll(moParser.parse(xmlEventReader));

   return new AppConfigurationEntry(codeName, controlFlag, options);
}
 
Example 15
Source File: Krb5LoginConfiguration.java    From directory-ldap-api with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of Krb5LoginConfiguration.
 */
public Krb5LoginConfiguration()
{
    String loginModule = "com.sun.security.auth.module.Krb5LoginModule";

    HashMap<String, Object> options = new HashMap<>();

    // TODO: this only works for Sun JVM
    options.put( "refreshKrb5Config", "true" );

    LoginModuleControlFlag flag = LoginModuleControlFlag.REQUIRED;
    configList[0] = new AppConfigurationEntry( loginModule, flag, options );
}
 
Example 16
Source File: AuthenticationConfigParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private AppConfigurationEntry getEntry(XMLStreamReader reader) throws XMLStreamException
{
   Map<String, Object> options = new HashMap<String, Object>();
   String codeName = null;
   LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;

   final int count = reader.getAttributeCount();
   if (count < 2)
   {
      Set<org.jboss.security.config.Attribute> set = new HashSet<org.jboss.security.config.Attribute>();
      set.add(org.jboss.security.config.Attribute.CODE);
      set.add(org.jboss.security.config.Attribute.FLAG);
      throw StaxParserUtil.missingRequired(reader, set);
   }
   for (int i = 0; i < count; i++)
   {
      final String value = reader.getAttributeValue(i);
      final org.jboss.security.config.Attribute attribute = org.jboss.security.config.Attribute.forName(reader
            .getAttributeLocalName(i));
      switch (attribute)
      {
         case CODE : {
            // check if it's a known login module
            if (loginModulesMap.containsKey(value))
                codeName = loginModulesMap.get(value);
            else
                codeName = value;
            break;
         }
         case FLAG : {
            controlFlag = getControlFlag(value);
            break;
         }
         default :
            throw StaxParserUtil.unexpectedAttribute(reader, i);
      }
   }
   //See if there are options
   ModuleOptionParser moParser = new ModuleOptionParser();
   options.putAll(moParser.parse(reader));

   return new AppConfigurationEntry(codeName, controlFlag, options);
}
 
Example 17
Source File: UserGroupInformation.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Create a UserGroupInformation from a Kerberos ticket cache.
 * 
 * @param user                The principal name to load from the ticket
 *                            cache
 * @param ticketCachePath     the path to the ticket cache file
 *
 * @throws IOException        if the kerberos login fails
 */
@InterfaceAudience.Public
@InterfaceStability.Evolving
public static UserGroupInformation getUGIFromTicketCache(
          String ticketCache, String user) throws IOException {
  if (!isAuthenticationMethodEnabled(AuthenticationMethod.KERBEROS)) {
    return getBestUGI(null, user);
  }
  try {
    Map<String,String> krbOptions = new HashMap<String,String>();
    if (IBM_JAVA) {
      krbOptions.put("useDefaultCcache", "true");
      // The first value searched when "useDefaultCcache" is used.
      System.setProperty("KRB5CCNAME", ticketCache);
    } else {
      krbOptions.put("doNotPrompt", "true");
      krbOptions.put("useTicketCache", "true");
      krbOptions.put("useKeyTab", "false");
      krbOptions.put("ticketCache", ticketCache);
    }
    krbOptions.put("renewTGT", "false");
    krbOptions.putAll(HadoopConfiguration.BASIC_JAAS_OPTIONS);
    AppConfigurationEntry ace = new AppConfigurationEntry(
        KerberosUtil.getKrb5LoginModuleName(),
        LoginModuleControlFlag.REQUIRED,
        krbOptions);
    DynamicConfiguration dynConf =
        new DynamicConfiguration(new AppConfigurationEntry[]{ ace });
    LoginContext login = newLoginContext(
        HadoopConfiguration.USER_KERBEROS_CONFIG_NAME, null, dynConf);
    login.login();

    Subject loginSubject = login.getSubject();
    Set<Principal> loginPrincipals = loginSubject.getPrincipals();
    if (loginPrincipals.isEmpty()) {
      throw new RuntimeException("No login principals found!");
    }
    if (loginPrincipals.size() != 1) {
      LOG.warn("found more than one principal in the ticket cache file " +
        ticketCache);
    }
    User ugiUser = new User(loginPrincipals.iterator().next().getName(),
        AuthenticationMethod.KERBEROS, login);
    loginSubject.getPrincipals().add(ugiUser);
    UserGroupInformation ugi = new UserGroupInformation(loginSubject);
    ugi.setLogin(login);
    ugi.setAuthenticationMethod(AuthenticationMethod.KERBEROS);
    return ugi;
  } catch (LoginException le) {
    throw new IOException("failure to login using ticket cache file " +
        ticketCache, le);
  }
}
 
Example 18
Source File: AuthenticationJASPIConfigParser.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private AppConfigurationEntry getJAASEntry(XMLStreamReader reader) throws XMLStreamException
{
   Map<String, Object> options = new HashMap<String, Object>();
   String codeName = null;
   LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;

   final int count = reader.getAttributeCount();
   if (count < 2)
   {
      Set<org.jboss.security.config.Attribute> set = new HashSet<org.jboss.security.config.Attribute>();
      set.add(org.jboss.security.config.Attribute.CODE);
      set.add(org.jboss.security.config.Attribute.FLAG);
      throw StaxParserUtil.missingRequired(reader, set);
   }
   for (int i = 0; i < count; i++)
   {
      final String value = reader.getAttributeValue(i);
      final org.jboss.security.config.Attribute attribute = org.jboss.security.config.Attribute.forName(reader
            .getAttributeLocalName(i));
      switch (attribute)
      {
         case CODE : {
            // check if it's a known login module
            if (AuthenticationConfigParser.loginModulesMap.containsKey(value))
                codeName = AuthenticationConfigParser.loginModulesMap.get(value);
            else
                codeName = value;
            break;
         }
         case FLAG : {
            controlFlag = getControlFlag(value);
            break;
         }
         default :
            throw StaxParserUtil.unexpectedAttribute(reader, i);
      }
   }
   //See if there are options
   ModuleOptionParser moParser = new ModuleOptionParser();
   options.putAll(moParser.parse(reader));

   return new AppConfigurationEntry(codeName, controlFlag, options);
}
 
Example 19
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
public Authentication getPamAuthentication(Authentication authentication) {
	try {
		String rangerLdapDefaultRole = PropertiesUtil.getProperty(
				"ranger.ldap.default.role", "ROLE_USER");
		DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider();
		String loginModuleName = "org.apache.ranger.authentication.unix.jaas.PamLoginModule";
		LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;
		Map<String, String> options = PropertiesUtil.getPropertiesMap();

		if (!options.containsKey("ranger.pam.service"))
			options.put("ranger.pam.service", "ranger-admin");

		AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(
				loginModuleName, controlFlag, options);
		AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry };
		Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<String, AppConfigurationEntry[]>();
		appConfigurationEntriesOptions.put("SPRINGSECURITY",
				appConfigurationEntries);
		Configuration configuration = new InMemoryConfiguration(
				appConfigurationEntriesOptions);
		jaasAuthenticationProvider.setConfiguration(configuration);
		RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter();
		RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter };
		jaasAuthenticationProvider.setAuthorityGranters(authorityGranters);
		jaasAuthenticationProvider.afterPropertiesSet();
		String userName = authentication.getName();
		String userPassword = "";
		if (authentication.getCredentials() != null) {
			userPassword = authentication.getCredentials().toString();
		}

		// getting user authenticated
		if (userName != null && userPassword != null
				&& !userName.trim().isEmpty()
				&& !userPassword.trim().isEmpty()) {
			final List<GrantedAuthority> grantedAuths = new ArrayList<>();
			grantedAuths.add(new SimpleGrantedAuthority(
					rangerLdapDefaultRole));
			final UserDetails principal = new User(userName, userPassword,
					grantedAuths);
			final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
					principal, userPassword, grantedAuths);
			authentication = jaasAuthenticationProvider
					.authenticate(finalAuthentication);
			authentication=getAuthenticationWithGrantedAuthority(authentication);
			return authentication;
		} else {
			return authentication;
		}
	} catch (Exception e) {
		logger.debug("Pam Authentication Failed:", e);
	}
	return authentication;
}
 
Example 20
Source File: RangerAuthenticationProvider.java    From ranger with Apache License 2.0 4 votes vote down vote up
public Authentication getUnixAuthentication(Authentication authentication) {

		try {
			String rangerLdapDefaultRole = PropertiesUtil.getProperty(
					"ranger.ldap.default.role", "ROLE_USER");
			DefaultJaasAuthenticationProvider jaasAuthenticationProvider = new DefaultJaasAuthenticationProvider();
			String loginModuleName = "org.apache.ranger.authentication.unix.jaas.RemoteUnixLoginModule";
			LoginModuleControlFlag controlFlag = LoginModuleControlFlag.REQUIRED;
			Map<String, String> options = PropertiesUtil.getPropertiesMap();
			AppConfigurationEntry appConfigurationEntry = new AppConfigurationEntry(
					loginModuleName, controlFlag, options);
			AppConfigurationEntry[] appConfigurationEntries = new AppConfigurationEntry[] { appConfigurationEntry };
			Map<String, AppConfigurationEntry[]> appConfigurationEntriesOptions = new HashMap<String, AppConfigurationEntry[]>();
			appConfigurationEntriesOptions.put("SPRINGSECURITY",
					appConfigurationEntries);
			Configuration configuration = new InMemoryConfiguration(
					appConfigurationEntriesOptions);
			jaasAuthenticationProvider.setConfiguration(configuration);
			RoleUserAuthorityGranter authorityGranter = new RoleUserAuthorityGranter();
			RoleUserAuthorityGranter[] authorityGranters = new RoleUserAuthorityGranter[] { authorityGranter };
			jaasAuthenticationProvider.setAuthorityGranters(authorityGranters);
			jaasAuthenticationProvider.afterPropertiesSet();
			String userName = authentication.getName();
			String userPassword = "";
			if (authentication.getCredentials() != null) {
				userPassword = authentication.getCredentials().toString();
			}

			// getting user authenticated
			if (userName != null && userPassword != null
					&& !userName.trim().isEmpty()
					&& !userPassword.trim().isEmpty()) {
				final List<GrantedAuthority> grantedAuths = new ArrayList<>();
				grantedAuths.add(new SimpleGrantedAuthority(
						rangerLdapDefaultRole));
				final UserDetails principal = new User(userName, userPassword,
						grantedAuths);
				final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(
						principal, userPassword, grantedAuths);
				authentication = jaasAuthenticationProvider
						.authenticate(finalAuthentication);
				authentication=getAuthenticationWithGrantedAuthority(authentication);
				return authentication;
			} else {
				return authentication;
			}
		} catch (Exception e) {
			logger.debug("Unix Authentication Failed:", e);
		}

		return authentication;
	}