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

来源:互联网 发布:网络摄监控系统图 编辑:程序博客网 时间:2024/06/11 23:07

==为Spring Security配置以JDBC为支撑的用户存储==

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

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


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



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

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

Spring Security提供了3个加密模块的实现:BCryptPasswordEncoder、NoOpPasswordEncoder和StandardPasswordEncoder.。

//基于数据库表进行认证@Autowiredprivate DataSource dataSource; //通过自动装配获取配置的dataSource对象@Overrideprotected 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()方法中进行的。

0 0
原创粉丝点击