zoukankan      html  css  js  c++  java
  • 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事件广播
    浏览器中文乱码,组合项目中部分模块乱码
    SpringSecurity加密Salt
    Linux服务器Java输出文件中文乱码
    重定向监听端口并持久化路由配置
    Mac下文件编码转换
    Shell之内容匹配与格式输出
    [leetcode]Scramble String
    [leetcode]Decode Ways
    [leetcode]Valid Palindrome
  • 原文地址:https://www.cnblogs.com/shamgod/p/5250050.html
Copyright © 2011-2022 走看看