基础部分参见:
http://suene.iteye.com/blog/1829807
<authentication-manager>
<authentication-provider ref="authenticationProvider" />
</authentication-manager>
<beans:bean id="authenticationProvider" class="org.e.simple.authtication.LdapAndDbAuthenticationProvider">
<beans:property name="authenticateByLdap" value="false" />
<beans:property name="url" value="ldap://localhost:10389/dc=example,dc=com" />
<beans:property name="userSearchBase" value="ou=Users" />
<beans:property name="hash" value="{sha}" />
</beans:bean>
/** 先根据属性 {@link #authenticateByLdap }, 是否使用 LDAP 验证 用户信息. 否则使用数据库查询验证用户.<br/>
*
* 如果验证成功,则以数据库获取用户的权限. */
public class LdapAndDbAuthenticationProvider implements AuthenticationProvider
{
private static final Logger logger = LoggerFactory.getLogger(LdapAndDbAuthenticationProvider.class);
@Autowired
private UserRepository userRepository;
/** LDAP server */
private DefaultSpringSecurityContextSource contextSource;
/** LdapAuthenticator */
private LdapAuthenticator authenticator;
/** 是否使用 LDAP 验证用户. */
private boolean authenticateByLdap;
// ldap url
private String url;
// <user-dn-pattern/>
private String userDnPattern;
// <user-search-filter/>
private String userSearchFilter = "(uid={0})";
// <user-search-base/>
private String userSearchBase = "";
// <password-compare />
// 是否验证密码.
private boolean passwordCompar = true;
// <password-attribute/>
private String passwordAttribute = "userPassword";
// password-compare : hash
// default = plaintext
// 参考 org.springframework.security.config.authentication.PasswordEncoderParser.ENCODER_CLASSES
private String hash = "plaintext";
// password-encoder : base64
private boolean useBase64;
// 获取对应的 pwEncoder
private PasswordEncoder pwEncoder;
@PostConstruct
public void init() throws Exception
{
if (passwordCompar)
{
AbstractBeanDefinition def = (AbstractBeanDefinition) PasswordEncoderParser.createPasswordEncoderBeanDefinition(hash, useBase64);
Object pwEncoderObj = def.getBeanClass().newInstance();
if (pwEncoderObj instanceof BaseDigestPasswordEncoder)
{
((BaseDigestPasswordEncoder) pwEncoderObj).setEncodeHashAsBase64(useBase64);
}
if (pwEncoderObj instanceof PasswordEncoder)
{
this.pwEncoder = (PasswordEncoder) pwEncoderObj;
}
}
if (authenticateByLdap)
{
contextSource = new DefaultSpringSecurityContextSource(url);
contextSource.afterPropertiesSet();
LdapUserSearch userSearch = new FilterBasedLdapUserSearch(this.userSearchBase, this.userSearchFilter, contextSource);
String[] userDnPatternArray = new String[0];
if (StringUtils.hasText(userDnPattern))
{
userDnPatternArray = new String[]
{ userDnPattern };
}
if (passwordCompar)
{
authenticator = new PasswordComparisonAuthenticator(contextSource);
((PasswordComparisonAuthenticator) authenticator).setPasswordAttributeName(passwordAttribute);
((PasswordComparisonAuthenticator) authenticator).setPasswordEncoder((PasswordEncoder) pwEncoder);
((PasswordComparisonAuthenticator) authenticator).setUserDnPatterns(userDnPatternArray);
((PasswordComparisonAuthenticator) authenticator).setUserSearch(userSearch);
} else
{
authenticator = new BindAuthenticator(contextSource);
((BindAuthenticator) authenticator).setUserDnPatterns(userDnPatternArray);
((BindAuthenticator) authenticator).setUserSearch(userSearch);
}
}
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException
{
final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
String username = userToken.getName();
String password = (String) authentication.getCredentials();
if (!StringUtils.hasLength(username))
{
throw new BadCredentialsException("Empty Username");
}
if (!StringUtils.hasLength(password))
{
throw new BadCredentialsException("Empty Password");
}
List<User> users = userRepository.findByUsername(username);
if (CollectionUtils.isEmpty(users))
{
throw new BadCredentialsException("Bad credentials");
}
UserDetails user = users.get(0);
if (authenticateByLdap)
{
doLdapAuthentication(userToken);
} else
{
if (passwordCompar)
{
String encodePassword = pwEncoder.encodePassword(password, null);
if (!encodePassword.equals(user.getPassword()))
{
throw new BadCredentialsException("Bad credentials");
}
}
}
return createSuccessfulAuthentication(userToken, user);
}
protected DirContextOperations doLdapAuthentication(UsernamePasswordAuthenticationToken authentication)
{
try
{
return authenticator.authenticate(authentication);
} catch (Exception e)
{
logger.error(e.getMessage(), e);
throw new BadCredentialsException("Bad credentials");
}
}
@Override
public boolean supports(Class<?> authentication)
{
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
protected Authentication createSuccessfulAuthentication(UsernamePasswordAuthenticationToken authentication, UserDetails user)
{
Object password = authentication.getCredentials();
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
result.setDetails(authentication.getDetails());
return result;
}
// set method...
}
分享到:
相关推荐
LDAP - spring-security-ldap.jar 26 ACL - spring-security-acl.jar 26 CAS - spring-security-cas.jar 26 OpenID - spring-security-openid.jar 26 测试 - spring-security-test.jar 26 2.4.4检出来源 26 3. ...
Enable AAA on R2 and configure all logins to authenticate using the AAA TACACS+ server and if not available, then use the local database. Step 5. Configure the line console to use the defined AAA ...
Spring Security OTP插件 Spring Security OTP插件使用Spring Security向应用程序添加了一次性密码(OTP)功能。 一次性密码令牌可以用作认证的带外第二因素。 该插件支持通过电子邮件和SMS文本传输OTP令牌。 组件 ...
vue-authenticate, 简单 Vue.js 身份验证库 [ WARNING ]: 自述文件目前正在重写中,即将发布。身份验证 使用 Vue.js,提供本地登录/注册,以及使用 Github,Facebook,Google和其他OAuth提供商,可以方便地为提供...
Over 40 recipes for creating cloud-ready Java web applications with Spring MVC About This Book Configure Spring MVC to build logic-less controllers that transparently support the most advanced web ...
尽可能贴合 Spring Security 的设计 实现注解权限控制 登入: POST 用户名密码到 \login 请求到达 JwtAuthenticationFilter 中的 attemptAuthentication() 方法,获取 request 中的 POST 参数,包装成一个 ...
之前用ldap.jar查询记录最多只能1000行,后面在网上找到了个方法,可以自定义最大记录数,代码是这样的: [java] view plain copy netscape.ldap.LDAPConnection lc = new netscape.ldap.LDAPConnection(); lc....
确保database.properties中hibernate.show_sql=false log4j.propertis文件中是否设置成ERROR级别 2、把tomcat安装为windows服务的时候,要把jvm内存设置成1G,同时一定要把这些参数加进去。 -XX:PermSize=64M -XX:...
确保database.properties中hibernate.show_sql=false log4j.propertis文件中是否设置成ERROR级别 2、把tomcat安装为windows服务的时候,要把jvm内存设置成1G,同时一定要把这些参数加进去。 -XX:PermSize=64M -XX:...
ldapinitialdircontextnpe 在JVM中复制可疑缺陷会影响Java的LDAP支持[1]。... java.lang.NullPointerException at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:300) at com.sun.jndi.ldap.LdapCtx.c
在与银联的对接中,调试过程中报错或使用类似登入加密:java.lang.SecurityException: JCE cannot authenticate the provider BC 进行问题解决,里面包含 bcprov-jdk16-143.jar与bcprov-jdk15-135.jar与具体文件存放...
Understanding Database Normalization. . . . . . . . . . . . . . . . . . . . 506 Applying the Normal Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . 506 Normalizing the my_contacts Table. . ...
Contents About the Author...............................................................................................xix About the Technical Reviewer and Contributing Author.................xxi ...
Chapter 7 Developing a Database Security Plan About the Security Policy and Security Plan Types of Accounts Standards for Accounts Standards for Usernames Standards for Passwords Standards for ...
JWTSpring安全演示关于这是一个将与和结合使用的演示。 我完全重写了我的第一个版本。 现在,该解决方案基于的代码库。 我尝试提取JWT身份验证所需的最少配置和类,并进行了一些更改。要求该演示是使用Maven 3.6.x和...
app版本管理,(热更新)前后端分离,vue page分页功能,authenticate 权限控制,accessto.zip
-u, --username Authenticate with NATS using username. -p, --password Authenticate with NATS using password. -t, --token Authenticate with NATS using a token. -c, --credentials Authenticate with ...
kubernetes-ldap 适用于Kubernetes:trade_mark:的轻型目录访问协议(LDAP) 入门 该项目为Kubernetes提供了LDAP身份验证Webhook。 当前的实现公开了两个端点: / authenticate:处理来自Kubernetes的令牌身份验证...
LDAP绒毛 为各种后端提供LDAP查询的多种实现 支持Active Directory,FreeIPA和posix风格的LDAP 安装 现在可以在rubygems.org存储库中找到, $ gem install ldap_fluff Rails应用程序配置 您必须对gem进行一些...
普林尼·利伯拉托(Pliny Librato) 一个度量记者后端的。 此后端会将报告的指标推送到队列中,然后定期异步... authenticate ( Config . librato_email , Config . librato_key ) Pliny :: Metrics . backends = [ Pli