Tabnine Logo
JaasAuthenticationProvider
Code IndexAdd Tabnine to your IDE (free)

How to use
JaasAuthenticationProvider
in
org.springframework.security.authentication.jaas

Best Java code snippets using org.springframework.security.authentication.jaas.JaasAuthenticationProvider (Showing top 20 results out of 315)

origin: spring-projects/spring-security

/**
 * Publishes the {@link JaasAuthenticationFailedEvent}. Can be overridden by
 * subclasses for different functionality
 *
 * @param token The authentication token being processed
 * @param ase The excetion that caused the authentication failure
 */
@Override
protected void publishFailureEvent(UsernamePasswordAuthenticationToken token,
    AuthenticationException ase) {
  // exists for passivity (the superclass does a null check before publishing)
  getApplicationEventPublisher()
      .publishEvent(new JaasAuthenticationFailedEvent(token, ase));
}
origin: spring-projects/spring-security

@Test
public void detectsMissingLoginConfig() throws Exception {
  JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider();
  myJaasProvider.setApplicationEventPublisher(context);
  myJaasProvider.setAuthorityGranters(jaasProvider.getAuthorityGranters());
  myJaasProvider.setCallbackHandlers(jaasProvider.getCallbackHandlers());
  myJaasProvider.setLoginContextName(jaasProvider.getLoginContextName());
  try {
    myJaasProvider.afterPropertiesSet();
    fail("Should have thrown ApplicationContextException");
  }
  catch (IllegalArgumentException expected) {
    assertThat(expected.getMessage().startsWith("loginConfig must be set on")).isTrue();
  }
}
origin: spring-projects/spring-security

@Override
public void afterPropertiesSet() throws Exception {
  // the superclass is not called because it does additional checks that are
  // non-passive
  Assert.hasLength(getLoginContextName(),
      () -> "loginContextName must be set on " + getClass());
  Assert.notNull(this.loginConfig,
      () -> "loginConfig must be set on " + getClass());
  configureJaas(this.loginConfig);
  Assert.notNull(Configuration.getConfiguration(),
      "As per http://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html "
          + "\"If a Configuration object was set via the Configuration.setConfiguration method, then that object is "
          + "returned. Otherwise, a default Configuration object is returned\". Your JRE returned null to "
          + "Configuration.getConfiguration().");
}
origin: spring-projects/spring-security

@Test
public void testFull() throws Exception {
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
      "user", "password", AuthorityUtils.createAuthorityList("ROLE_ONE"));
  assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue();
  Authentication auth = jaasProvider.authenticate(token);
  assertThat(jaasProvider.getAuthorityGranters()).isNotNull();
  assertThat(jaasProvider.getCallbackHandlers()).isNotNull();
  assertThat(jaasProvider.getLoginConfig()).isNotNull();
  assertThat(jaasProvider.getLoginContextName()).isNotNull();
  Collection<? extends GrantedAuthority> list = auth.getAuthorities();
  Set<String> set = AuthorityUtils.authorityListToSet(list);
  assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE").isFalse();
  assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue();
  assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue();
  boolean foundit = false;
  for (GrantedAuthority a : list) {
    if (a instanceof JaasGrantedAuthority) {
      JaasGrantedAuthority grant = (JaasGrantedAuthority) a;
      assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority").isNotNull();
      foundit = true;
    }
  }
  assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue();
  assertThat(eventCheck.successEvent).as("Success event should be fired").isNotNull();
  assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal").isEqualTo(auth);
  assertThat(eventCheck.failedEvent).as("Failure event should not be fired").isNull();
}
origin: spring-projects/spring-security

private void testConfigureJaasCase(JaasAuthenticationProvider p1,
    JaasAuthenticationProvider p2) throws Exception {
  p1.setLoginConfig(new ClassPathResource(resolveConfigFile("/test1.conf")));
  p1.setLoginContextName("test1");
  p1.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {
      new TestCallbackHandler(), new JaasNameCallbackHandler(),
      new JaasPasswordCallbackHandler() });
  p1.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
  p1.afterPropertiesSet();
  testAuthenticate(p1);
  p2.setLoginConfig(new ClassPathResource(resolveConfigFile("/test2.conf")));
  p2.setLoginContextName("test2");
  p2.setCallbackHandlers(new JaasAuthenticationCallbackHandler[] {
      new TestCallbackHandler(), new JaasNameCallbackHandler(),
      new JaasPasswordCallbackHandler() });
  p2.setAuthorityGranters(new AuthorityGranter[] { new TestAuthorityGranter() });
  p2.afterPropertiesSet();
  testAuthenticate(p2);
}
origin: spring-projects/spring-security

@Override
protected LoginContext createLoginContext(CallbackHandler handler)
    throws LoginException {
  return new LoginContext(getLoginContextName(), handler);
}
origin: org.apereo.cas/cas-server-webapp-config

/**
 * Configure jaas authentication provider.
 *
 * @param auth the auth
 * @param jaas the jaas
 * @throws Exception the exception
 */
protected void configureJaasAuthenticationProvider(final AuthenticationManagerBuilder auth,
                          final MonitorProperties.Endpoints.JaasSecurity jaas) throws Exception {
  val p = new JaasAuthenticationProvider();
  p.setLoginConfig(jaas.getLoginConfig());
  p.setLoginContextName(jaas.getLoginContextName());
  p.setRefreshConfigurationOnStartup(jaas.isRefreshConfigurationOnStartup());
  p.afterPropertiesSet();
  auth.authenticationProvider(p);
}
origin: spring-projects/spring-security

/**
 * Hook method for configuring Jaas.
 *
 * @param loginConfig URL to Jaas login configuration
 *
 * @throws IOException if there is a problem reading the config resource.
 */
protected void configureJaas(Resource loginConfig) throws IOException {
  configureJaasUsingLoop();
  if (this.refreshConfigurationOnStartup) {
    // Overcome issue in SEC-760
    Configuration.getConfiguration().refresh();
  }
}
origin: spring-projects/spring-security

/**
 * Loops through the login.config.url.1,login.config.url.2 properties looking for the
 * login configuration. If it is not set, it will be set to the last available
 * login.config.url.X property.
 *
 */
private void configureJaasUsingLoop() throws IOException {
  String loginConfigUrl = convertLoginConfigToUrl();
  boolean alreadySet = false;
  int n = 1;
  final String prefix = "login.config.url.";
  String existing;
  while ((existing = Security.getProperty(prefix + n)) != null) {
    alreadySet = existing.equals(loginConfigUrl);
    if (alreadySet) {
      break;
    }
    n++;
  }
  if (!alreadySet) {
    String key = prefix + n;
    log.debug("Setting security property [" + key + "] to: " + loginConfigUrl);
    Security.setProperty(key, loginConfigUrl);
  }
}
origin: spring-projects/spring-security

@Test
public void testLogout() throws Exception {
  MockLoginContext loginContext = new MockLoginContext(
      jaasProvider.getLoginContextName());
  JaasAuthenticationToken token = new JaasAuthenticationToken(null, null,
      loginContext);
  SecurityContext context = SecurityContextHolder.createEmptyContext();
  context.setAuthentication(token);
  SessionDestroyedEvent event = mock(SessionDestroyedEvent.class);
  when(event.getSecurityContexts()).thenReturn(Arrays.asList(context));
  jaasProvider.handleLogout(event);
  assertThat(loginContext.loggedOut).isTrue();
}
origin: spring-projects/spring-security

@Test
public void testConfigureJaas() throws Exception {
  testConfigureJaasCase(new JaasAuthenticationProvider(),
      new JaasAuthenticationProvider());
}
origin: org.springframework.security/spring-security-core

@Override
protected LoginContext createLoginContext(CallbackHandler handler)
    throws LoginException {
  return new LoginContext(getLoginContextName(), handler);
}
origin: org.springframework.security/spring-security-core

/**
 * Hook method for configuring Jaas.
 *
 * @param loginConfig URL to Jaas login configuration
 *
 * @throws IOException if there is a problem reading the config resource.
 */
protected void configureJaas(Resource loginConfig) throws IOException {
  configureJaasUsingLoop();
  if (this.refreshConfigurationOnStartup) {
    // Overcome issue in SEC-760
    Configuration.getConfiguration().refresh();
  }
}
origin: org.springframework.security/spring-security-core

/**
 * Loops through the login.config.url.1,login.config.url.2 properties looking for the
 * login configuration. If it is not set, it will be set to the last available
 * login.config.url.X property.
 *
 */
private void configureJaasUsingLoop() throws IOException {
  String loginConfigUrl = convertLoginConfigToUrl();
  boolean alreadySet = false;
  int n = 1;
  final String prefix = "login.config.url.";
  String existing;
  while ((existing = Security.getProperty(prefix + n)) != null) {
    alreadySet = existing.equals(loginConfigUrl);
    if (alreadySet) {
      break;
    }
    n++;
  }
  if (!alreadySet) {
    String key = prefix + n;
    log.debug("Setting security property [" + key + "] to: " + loginConfigUrl);
    Security.setProperty(key, loginConfigUrl);
  }
}
origin: spring-projects/spring-security

@Test
public void detectsMissingLoginContextName() throws Exception {
  JaasAuthenticationProvider myJaasProvider = new JaasAuthenticationProvider();
  myJaasProvider.setApplicationEventPublisher(context);
  myJaasProvider.setAuthorityGranters(jaasProvider.getAuthorityGranters());
  myJaasProvider.setCallbackHandlers(jaasProvider.getCallbackHandlers());
  myJaasProvider.setLoginConfig(jaasProvider.getLoginConfig());
  myJaasProvider.setLoginContextName(null);
  try {
    myJaasProvider.afterPropertiesSet();
    fail("Should have thrown IllegalArgumentException");
  }
  catch (IllegalArgumentException expected) {
    assertThat(expected.getMessage()).startsWith("loginContextName must be set on");
  }
  myJaasProvider.setLoginContextName("");
  try {
    myJaasProvider.afterPropertiesSet();
    fail("Should have thrown IllegalArgumentException");
  }
  catch (IllegalArgumentException expected) {
    assertThat(expected.getMessage().startsWith("loginContextName must be set on"));
  }
}
origin: org.springframework.security/spring-security-core

@Override
public void afterPropertiesSet() throws Exception {
  // the superclass is not called because it does additional checks that are
  // non-passive
  Assert.hasLength(getLoginContextName(),
      () -> "loginContextName must be set on " + getClass());
  Assert.notNull(this.loginConfig,
      () -> "loginConfig must be set on " + getClass());
  configureJaas(this.loginConfig);
  Assert.notNull(Configuration.getConfiguration(),
      "As per http://java.sun.com/j2se/1.5.0/docs/api/javax/security/auth/login/Configuration.html "
          + "\"If a Configuration object was set via the Configuration.setConfiguration method, then that object is "
          + "returned. Otherwise, a default Configuration object is returned\". Your JRE returned null to "
          + "Configuration.getConfiguration().");
}
origin: org.springframework.security/spring-security-core

/**
 * Publishes the {@link JaasAuthenticationFailedEvent}. Can be overridden by
 * subclasses for different functionality
 *
 * @param token The authentication token being processed
 * @param ase The excetion that caused the authentication failure
 */
@Override
protected void publishFailureEvent(UsernamePasswordAuthenticationToken token,
    AuthenticationException ase) {
  // exists for passivity (the superclass does a null check before publishing)
  getApplicationEventPublisher()
      .publishEvent(new JaasAuthenticationFailedEvent(token, ase));
}
origin: apache/servicemix-bundles

@Override
protected LoginContext createLoginContext(CallbackHandler handler)
    throws LoginException {
  return new LoginContext(getLoginContextName(), handler);
}
origin: org.springframework.security/org.springframework.security.core

/**
 * Hook method for configuring Jaas.
 *
 * @param loginConfig URL to Jaas login configuration
 *
 * @throws IOException if there is a problem reading the config resource.
 */
protected void configureJaas(Resource loginConfig) throws IOException {
  configureJaasUsingLoop();
  if (refreshConfigurationOnStartup) {
    // Overcome issue in SEC-760
    Configuration.getConfiguration().refresh();
  }
}
origin: org.springframework.security/org.springframework.security.core

/**
 * Loops through the login.config.url.1,login.config.url.2 properties looking for the login configuration.
 * If it is not set, it will be set to the last available login.config.url.X property.
 *
 */
private void configureJaasUsingLoop() throws IOException {
  String loginConfigUrl = convertLoginConfigToUrl();
  boolean alreadySet = false;
  int n = 1;
  final String prefix = "login.config.url.";
  String existing;
  while ((existing = Security.getProperty(prefix + n)) != null) {
    alreadySet = existing.equals(loginConfigUrl);
    if (alreadySet) {
      break;
    }
    n++;
  }
  if (!alreadySet) {
    String key = prefix + n;
    log.debug("Setting security property [" + key + "] to: " + loginConfigUrl);
    Security.setProperty(key, loginConfigUrl);
  }
}
org.springframework.security.authentication.jaasJaasAuthenticationProvider

Javadoc

An AuthenticationProvider implementation that retrieves user details from a JAAS login configuration.

This AuthenticationProvider is capable of validating org.springframework.security.authentication.UsernamePasswordAuthenticationTokenrequests contain the correct username and password.

This implementation is backed by a JAAS configuration. The loginConfig property must be set to a given JAAS configuration file. This setter accepts a Spring org.springframework.core.io.Resource instance. It should point to a JAAS configuration file containing an index matching the #setLoginContextName(java.lang.String) property.

For example: If this JaasAuthenticationProvider were configured in a Spring WebApplicationContext the xml to set the loginConfiguration could be as follows...

 
<property name="loginConfig"> 
<value>/WEB-INF/login.conf</value> 
</property> 

The loginContextName should coincide with a given index in the loginConfig specifed. The loginConfig file used in the JUnit tests appears as the following...

 
JAASTest { 
org.springframework.security.authentication.jaas.TestLoginModule required; 
}; 
Using the example login configuration above, the loginContextName property would be set as JAASTest...
 
<property name="loginContextName"> <value>JAASTest</value> </property> 

When using JAAS login modules as the authentication source, sometimes the LoginContext will require CallbackHandlers. The JaasAuthenticationProvider uses an internal CallbackHandler to wrap the JaasAuthenticationCallbackHandlers configured in the ApplicationContext. When the LoginContext calls the internal CallbackHandler, control is passed to each JaasAuthenticationCallbackHandler for each Callback passed.

JaasAuthenticationCallbackHandlers are passed to the JaasAuthenticationProvider through the #setCallbackHandlers(org.springframework.security.authentication.jaas.JaasAuthenticationCallbackHandler[]) property.

 
<property name="callbackHandlers"> 
<list> 
<bean class="org.springframework.security.authentication.jaas.TestCallbackHandler"/> 
<bean class=" 
JaasNameCallbackHandler"/> 
<bean class=" 
JaasPasswordCallbackHandler"/> 
</list> 
</property> 

After calling LoginContext.login(), the JaasAuthenticationProvider will retrieve the returned Principals from the Subject (LoginContext.getSubject().getPrincipals). Each returned principal is then passed to the configured AuthorityGranters. An AuthorityGranter is a mapping between a returned Principal, and a role name. If an AuthorityGranter wishes to grant an Authorization a role, it returns that role name from it's AuthorityGranter#grant(java.security.Principal) method. The returned role will be applied to the Authorization object as a GrantedAuthority.

AuthorityGranters are configured in spring xml as follows...

 
<property name="authorityGranters"> 
<list> 
<bean class="org.springframework.security.authentication.jaas.TestAuthorityGranter"/> 
</list> 
</property> 
A configuration note: The JaasAuthenticationProvider uses the security properites "login.config.url.X" to configure jaas. If you would like to customize the way Jaas gets configured, create a subclass of this and override the #configureJaas(Resource) method.

Most used methods

  • getApplicationEventPublisher
  • getLoginContextName
  • configureJaas
    Hook method for configuring Jaas.
  • configureJaasUsingLoop
    Loops through the login.config.url.1,login.config.url.2 properties looking for the login configurati
  • convertLoginConfigToUrl
  • <init>
  • afterPropertiesSet
  • setLoginConfig
    Set the JAAS login configuration file.
  • setLoginContextName
  • authenticate
  • getAuthorityGranters
  • getCallbackHandlers
  • getAuthorityGranters,
  • getCallbackHandlers,
  • getLoginConfig,
  • getLoginExceptionResolver,
  • handleLogout,
  • setApplicationEventPublisher,
  • setAuthorityGranters,
  • setCallbackHandlers,
  • setLoginExceptionResolver,
  • setRefreshConfigurationOnStartup

Popular in Java

  • Running tasks concurrently on multiple threads
  • startActivity (Activity)
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • scheduleAtFixedRate (Timer)
  • BufferedImage (java.awt.image)
    The BufferedImage subclass describes an java.awt.Image with an accessible buffer of image data. All
  • Scanner (java.util)
    A parser that parses a text string of primitive types and strings with the help of regular expressio
  • Callable (java.util.concurrent)
    A task that returns a result and may throw an exception. Implementors define a single method with no
  • ImageIO (javax.imageio)
  • StringUtils (org.apache.commons.lang)
    Operations on java.lang.String that arenull safe. * IsEmpty/IsBlank - checks if a String contains
  • LogFactory (org.apache.commons.logging)
    Factory for creating Log instances, with discovery and configuration features similar to that employ
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now