您的位置:首页 > 数据库

4.基于数据库表进行认证

2016-07-21 17:42 519 查看
==为Spring Security配置以JDBC为支撑的用户存储==

可以是用jdbcAuthentication()方法,其所需的最少配置如下:

@Autowired
private DataSource dataSource;//通过自动装配获取配置的dataSource对象</span>
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth
.jdbcAuthentication()
.dataSource(dataSource);
}


使用最少配置在查找用户信息时所执行的默认SQL查询语句:①认证查询;②基本权限查询;③群组权限查询






==使用转码后的密码==


借助passwordEncoder()方法指定一个密码转码器

Spring Security提供了3个加密模块的实现:BCryptPasswordEncoder、NoOpPasswordEncoder和StandardPasswordEncoder.。
//基于数据库表进行认证
@Autowired
private DataSource dataSource; //通过自动装配获取配置的dataSource对象
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(	//自定义用户认证查询
"select username, password, true "+
"from Spitter where username=?")
.authoritiesByUsernameQuery(	//自定义基本权限查询
"select username, 'ROLE_USER' from Spitter where username=?")
//.passwordEncoder(new StandardPasswordEncoder("53cr3t"))<span style="white-space:pre">		</span>//使用内置加密模块
.passwordEncoder(new MD5());<span style="white-space:pre">	</span>//使用自定义的密码转换器
}

自定义的密码转码器需要实现PasswordEncoder接口:

public interface PasswordEncoder {
String encode(CharSequence rawPassword);
boolean matches(CharSequence rawPassword, String encodedPassword);
}不管使用何种转码器,数据库中的密码永远是不会解码的。所使用的策略都是:按照相同的算法对用户输入的密码进行转码,在与数据库中转码过的密码进行对比,对比的过程在PasswordEncoder的matches()方法中进行的。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: