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

How to use
DefaultLdapRealm
in
org.apache.shiro.realm.ldap

Best Java code snippets using org.apache.shiro.realm.ldap.DefaultLdapRealm (Showing top 20 results out of 315)

origin: apache/shiro

/**
 * Delegates to {@link #queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory)},
 * wrapping any {@link NamingException}s in a Shiro {@link AuthenticationException} to satisfy the parent method
 * signature.
 *
 * @param token the authentication token containing the user's principal and credentials.
 * @return the {@link AuthenticationInfo} acquired after a successful authentication attempt
 * @throws AuthenticationException if the authentication attempt fails or if a
 *                                 {@link NamingException} occurs.
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  AuthenticationInfo info;
  try {
    info = queryForAuthenticationInfo(token, getContextFactory());
  } catch (AuthenticationNotSupportedException e) {
    String msg = "Unsupported configured authentication mechanism";
    throw new UnsupportedAuthenticationMechanismException(msg, e);
  } catch (javax.naming.AuthenticationException e) {
    throw new AuthenticationException("LDAP authentication failed.", e);
  } catch (NamingException e) {
    String msg = "LDAP naming error while attempting to authenticate user.";
    throw new AuthenticationException(msg, e);
  }
  return info;
}
origin: apache/shiro

/**
 * Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see the
 * {@link #setUserDnTemplate(String) setUserDnTemplate} JavaDoc for a full explanation.
 *
 * @return the User Distinguished Name (DN) template to use when creating User DNs at runtime.
 */
public String getUserDnTemplate() {
  return getUserDn(USERDN_SUBSTITUTION_TOKEN);
}
origin: apache/shiro

protected DefaultLdapRealm getNewRealmUnderTest() {
  return new DefaultLdapRealm();
}
origin: apache/shiro

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  AuthorizationInfo info;
  try {
    info = queryForAuthorizationInfo(principals, getContextFactory());
  } catch (NamingException e) {
    String msg = "LDAP naming error while attempting to retrieve authorization for user [" + principals + "].";
    throw new AuthorizationException(msg, e);
  }
  return info;
}
origin: apache/shiro

principal = getLdapPrincipal(token);
  ctx = ldapContextFactory.getLdapContext(principal, credentials);
  return createAuthenticationInfo(token, principal, credentials, ctx);
} finally {
  LdapUtils.closeContext(ctx);
origin: apache/shiro

@Test
public void testUserDnTemplateSubstitution() throws NamingException {
  realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
  LdapContextFactory factory = createMock(LdapContextFactory.class);
  realm.setContextFactory(factory);
  Object expectedPrincipal = "uid=jsmith,ou=users,dc=mycompany,dc=com";
  expect(factory.getLdapContext(eq(expectedPrincipal), isA(Object.class))).andReturn(createNiceMock(LdapContext.class));
  replay(factory);
  realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret") );
  verify(factory);
}
origin: apache/shiro

@Test
public void testDefaultInstance() {
  assertTrue(realm.getCredentialsMatcher() instanceof AllowAllCredentialsMatcher);
  assertEquals(AuthenticationToken.class, realm.getAuthenticationTokenClass());
  assertTrue(realm.getContextFactory() instanceof JndiLdapContextFactory);
}
origin: apache/shiro

  @Test
  public void testGetUserDnWithOutPrefixAndSuffix() {
    realm = new DefaultLdapRealm() {
      @Override
      protected String getUserDnPrefix() {
        return null;
      }

      @Override
      protected String getUserDnSuffix() {
        return null;
      }
    };
    String principal = "foo";
    String userDn = realm.getUserDn(principal);
    assertEquals(principal, userDn);
  }
}
origin: org.neo4j/neo4j-security-enterprise

          : super.queryForAuthenticationInfo( token, ldapContextFactory );
securityLog.debug( withRealm( "Authenticated user '%s' against %s", token.getPrincipal(),
    serverString ) );
origin: apache/knox

@Override
//KNOX-534 overriding this method to be able to audit authentication exceptions
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws org.apache.shiro.authc.AuthenticationException {
 try {
  return super.doGetAuthenticationInfo(token);
 } catch ( org.apache.shiro.authc.AuthenticationException e ) {
  auditor.audit( Action.AUTHENTICATION , token.getPrincipal().toString(), ResourceType.PRINCIPAL, ActionOutcome.FAILURE, e.getMessage() );
  ShiroLog.failedLoginInfo(token);
  ShiroLog.failedLoginStackTrace(e);
  ShiroLog.failedLoginAttempt(e.getCause());
  throw e;
 }
}
origin: org.neo4j/neo4j-security-enterprise

@Override
protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals )
{
  try
  {
    AuthorizationInfo info = super.doGetAuthorizationInfo( principals );
    securityLog.debug( withRealm( "Queried for authorization info for user '%s'",
        principals.getPrimaryPrincipal() ) );
    return info;
  }
  catch ( AuthorizationException e )
  {
    securityLog.warn( withRealm( "Failed to get authorization info: '%s' caused by '%s'",
        e.getMessage(), e.getCause().getMessage() ) );
    return null;
  }
}
origin: apache/shiro

@Test(expected= AuthenticationException.class)
public void testGetAuthenticationInfoNamingException() throws NamingException {
  realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
  LdapContextFactory factory = createMock(LdapContextFactory.class);
  realm.setContextFactory(factory);
  expect(factory.getLdapContext(isA(Object.class), isA(Object.class)))
      .andThrow(new NamingException("Communication error."));
  replay(factory);
  realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret") );
}
origin: org.apache.shiro/shiro-core

protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  AuthorizationInfo info;
  try {
    info = queryForAuthorizationInfo(principals, getContextFactory());
  } catch (NamingException e) {
    String msg = "LDAP naming error while attempting to retrieve authorization for user [" + principals + "].";
    throw new AuthorizationException(msg, e);
  }
  return info;
}
origin: org.apache.shiro/shiro-core

principal = getLdapPrincipal(token);
  ctx = ldapContextFactory.getLdapContext(principal, credentials);
  return createAuthenticationInfo(token, principal, credentials, ctx);
} finally {
  LdapUtils.closeContext(ctx);
origin: apache/shiro

@Test(expected= AuthenticationException.class)
public void testGetAuthenticationInfoNamingAuthenticationException() throws NamingException {
  realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
  LdapContextFactory factory = createMock(LdapContextFactory.class);
  realm.setContextFactory(factory);
  expect(factory.getLdapContext(isA(Object.class), isA(Object.class)))
      .andThrow(new javax.naming.AuthenticationException("LDAP Authentication failed."));
  replay(factory);
  realm.getAuthenticationInfo(new UsernamePasswordToken("jsmith", "secret") );
}
origin: org.apache.shiro/shiro-core

/**
 * Delegates to {@link #queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory)},
 * wrapping any {@link NamingException}s in a Shiro {@link AuthenticationException} to satisfy the parent method
 * signature.
 *
 * @param token the authentication token containing the user's principal and credentials.
 * @return the {@link AuthenticationInfo} acquired after a successful authentication attempt
 * @throws AuthenticationException if the authentication attempt fails or if a
 *                                 {@link NamingException} occurs.
 */
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  AuthenticationInfo info;
  try {
    info = queryForAuthenticationInfo(token, getContextFactory());
  } catch (AuthenticationNotSupportedException e) {
    String msg = "Unsupported configured authentication mechanism";
    throw new UnsupportedAuthenticationMechanismException(msg, e);
  } catch (javax.naming.AuthenticationException e) {
    throw new AuthenticationException("LDAP authentication failed.", e);
  } catch (NamingException e) {
    String msg = "LDAP naming error while attempting to authenticate user.";
    throw new AuthenticationException(msg, e);
  }
  return info;
}
origin: apache/shiro

/**
 * Returns the principal to use when creating the LDAP connection for an authentication attempt.
 * <p/>
 * This implementation uses a heuristic: it checks to see if the specified token's
 * {@link AuthenticationToken#getPrincipal() principal} is a {@code String}, and if so,
 * {@link #getUserDn(String) converts it} from what is
 * assumed to be a raw uid or username {@code String} into a User DN {@code String}.  Almost all LDAP directories
 * expect the authentication connection to present a User DN and not an unqualified username or uid.
 * <p/>
 * If the token's {@code principal} is not a String, it is assumed to already be in the format supported by the
 * underlying {@link LdapContextFactory} implementation and the raw principal is returned directly.
 *
 * @param token the {@link AuthenticationToken} submitted during the authentication process
 * @return the User DN or raw principal to use to acquire the LdapContext.
 * @see LdapContextFactory#getLdapContext(Object, Object)
 */
protected Object getLdapPrincipal(AuthenticationToken token) {
  Object principal = token.getPrincipal();
  if (principal instanceof String) {
    String sPrincipal = (String) principal;
    return getUserDn(sPrincipal);
  }
  return principal;
}
origin: apache/shiro

/**
 * This test simulates that if a non-String principal (i.e. not a username) is passed as the LDAP principal, that
 * it is not altered into a User DN and is passed as-is.  This will allow principals to be things like X.509
 * certificates as well instead of only strings.
 *
 * @throws NamingException not thrown
 */
@Test
public void testGetAuthenticationInfoNonSimpleToken() throws NamingException {
  realm.setUserDnTemplate("uid={0},ou=users,dc=mycompany,dc=com");
  LdapContextFactory factory = createMock(LdapContextFactory.class);
  realm.setContextFactory(factory);
  final UUID userId = UUID.randomUUID();
  //ensure the userId is passed as-is:
  expect(factory.getLdapContext(eq(userId), isA(Object.class))).andReturn(createNiceMock(LdapContext.class));
  replay(factory);
  realm.getAuthenticationInfo(new AuthenticationToken() {
    public Object getPrincipal() {
      return userId;
    }
    public Object getCredentials() {
      return "secret";
    }
  });
  verify(factory);
}
origin: apache/shiro

@Test(expected=IllegalArgumentException.class)
public void testGetUserDnNullArgument() {
  realm.getUserDn(null);
}
origin: org.apache.shiro/shiro-core

/**
 * Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see the
 * {@link #setUserDnTemplate(String) setUserDnTemplate} JavaDoc for a full explanation.
 *
 * @return the User Distinguished Name (DN) template to use when creating User DNs at runtime.
 */
public String getUserDnTemplate() {
  return getUserDn(USERDN_SUBSTITUTION_TOKEN);
}
org.apache.shiro.realm.ldapDefaultLdapRealm

Javadoc

An LDAP org.apache.shiro.realm.Realm implementation utilizing Sun's/Oracle's JNDI API as an LDAP API. This is Shiro's default implementation for supporting LDAP, as using the JNDI API has been a common approach for Java LDAP support for many years.

This realm implementation and its backing JndiLdapContextFactory should cover 99% of all Shiro-related LDAP authentication and authorization needs. However, if it does not suit your needs, you might want to look into creating your own realm using an alternative, perhaps more robust, LDAP communication API, such as the Apache LDAP API.

Authentication During an authentication attempt, if the submitted AuthenticationToken's org.apache.shiro.authc.AuthenticationToken#getPrincipal() is a simple username, but the LDAP directory expects a complete User Distinguished Name (User DN) to establish a connection, the #setUserDnTemplate(String) property must be configured. If not configured, the property will pass the simple username directly as the User DN, which is often incorrect in most LDAP environments (maybe Microsoft ActiveDirectory being the exception). Authorization By default, authorization is effectively disabled due to the default #doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection) implementation returning null. If you wish to perform authorization based on an LDAP schema, you must subclass this one and override that method to reflect your organization's data model. Configuration This class primarily provides the #setUserDnTemplate(String) property to allow you to specify the your LDAP server's User DN format. Most other configuration is performed via the nested LdapContextFactory property.

For example, defining this realm in Shiro .ini:

 
[main] 
ldapRealm = org.apache.shiro.realm.ldap.DefaultLdapRealm 
ldapRealm.userDnTemplate = uid={0},ou=users,dc=mycompany,dc=com 
ldapRealm.contextFactory.url = ldap://ldapHost:389 
ldapRealm.contextFactory.authenticationMechanism = DIGEST-MD5 
ldapRealm.contextFactory.environment[some.obscure.jndi.key] = some value 
... 
The default #setContextFactory instance is a JndiLdapContextFactory. See that class's JavaDoc for more information on configuring the LDAP connection as well as specifying JNDI environment properties as necessary.

Most used methods

  • getContextFactory
    Returns the LdapContextFactory instance used to acquire connections to the LDAP directory during aut
  • getUserDn
    Returns the LDAP User Distinguished Name (DN) to use when acquiring an javax.naming.ldap.LdapContext
  • queryForAuthenticationInfo
    This implementation opens an LDAP connection using the token's #getLdapPrincipal(org.apache.shiro.au
  • <init>
    Default no-argument constructor that defaults the internal LdapContextFactory instance to a JndiLdap
  • createAuthenticationInfo
    Returns the AuthenticationInfo resulting from a Subject's successful LDAP authentication attempt. Th
  • doGetAuthenticationInfo
    Delegates to #queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken,LdapContextFacto
  • doGetAuthorizationInfo
  • getAuthenticationInfo
  • getAuthenticationTokenClass
  • getCredentialsMatcher
  • getLdapPrincipal
    Returns the principal to use when creating the LDAP connection for an authentication attempt. This i
  • getName
  • getLdapPrincipal,
  • getName,
  • getUserDnPrefix,
  • getUserDnSuffix,
  • getUserDnTemplate,
  • queryForAuthorizationInfo,
  • setAuthenticationTokenClass,
  • setContextFactory,
  • setCredentialsMatcher,
  • setUserDnTemplate

Popular in Java

  • Finding current android device location
  • getSharedPreferences (Context)
  • setContentView (Activity)
  • scheduleAtFixedRate (ScheduledExecutorService)
  • PrintStream (java.io)
    Fake signature of an existing Java class.
  • SortedSet (java.util)
    SortedSet is a Set which iterates over its elements in a sorted order. The order is determined eithe
  • ConcurrentHashMap (java.util.concurrent)
    A plug-in replacement for JDK1.5 java.util.concurrent.ConcurrentHashMap. This version is based on or
  • DataSource (javax.sql)
    An interface for the creation of Connection objects which represent a connection to a database. This
  • JPanel (javax.swing)
  • Options (org.apache.commons.cli)
    Main entry-point into the library. Options represents a collection of Option objects, which describ
  • Top 12 Jupyter Notebook extensions
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