一、
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.