SPRING IN ACTION 第4版笔记-第九章Securing web applications-003-把用户数据存在数据库
Posted shamgod
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SPRING IN ACTION 第4版笔记-第九章Securing web applications-003-把用户数据存在数据库相关的知识,希望对你有一定的参考价值。
一、
1.It’s quite common for user data to be stored in a relational database, accessed via JDBC . To configure Spring Security to authenticate against a JDBC -backed user store,you can use the jdbcAuthentication() method. The minimal configuration required is as follows:
1 在数据库保存用户数据 2 @Autowired 3 DataSource dataSource; 4 5 @Override 6 protected void configure(AuthenticationManagerBuilder auth) throws Exception { 7 auth.jdbcAuthentication().dataSource(dataSource); 8 }
The only thing you must configure is a DataSource so that it’s able to access the relational database. The DataSource is provided here via the magic of autowiring.
2.重写默认的查询语句
Although this minimal configuration will work, it makes some assumptions about your database schema. It expects that certain tables exist where user data will be kept. More specifically, the following snippet of code from Spring Security’s internals shows the SQL queries that will be performed when looking up user details:
1 public static final String DEF_USERS_BY_USERNAME_QUERY = 2 "select username,password,enabled " + 3 "from users " + 4 "where username = ?"; 5 public static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = 6 "select username,authority " + 7 "from authorities " + 8 "where username = ?"; 9 public static final String DEF_GROUP_AUTHORITIES_BY_USERNAME_QUERY = 10 "select g.id, g.group_name, ga.authority " + 11 "from groups g, group_members gm, group_authorities ga " + 12 "where gm.username = ? " + 13 "and g.id = ga.group_id " + 14 "and g.id = gm.group_id";
If you’re okay with defining and populating tables in your database that satisfy those queries, then there’s not much else for you to do. But chances are your database doesn’t look anything like this, and you’ll want more control over the queries. In that case, you can configure your own queries like this:
1 @Override 2 protected void configure(AuthenticationManagerBuilder auth) 3 throws Exception { 4 auth 5 .jdbcAuthentication() 6 .dataSource(dataSource) 7 .usersByUsernameQuery( 8 "select username, password, true " + 9 "from Spitter where username=?") 10 .authoritiesByUsernameQuery( 11 "select username, ‘ROLE_USER‘ from Spitter where username=?"); 12 }
3.
以上是关于SPRING IN ACTION 第4版笔记-第九章Securing web applications-003-把用户数据存在数据库的主要内容,如果未能解决你的问题,请参考以下文章
SPRING IN ACTION 第4版笔记-第九章Securing web applications-003-把用户数据存在数据库
SPRING IN ACTION 第4版笔记-第九章Securing web applications-002-把用户数据存在memory里(AuthenticationManagerBuilder(
SPRING IN ACTION 第4版笔记-第九章Securing web applications-008-使用非关系型数据库时如何验证用户(自定义UserService)
SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-008-SpEL介绍
SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-005-Bean的作用域@ScopeProxyMode
SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-011-注入AspectJ Aspect