欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于关系型数据库认证

程序员文章站 2022-06-02 18:35:14
...

在普通的JSP+Servlet应用中,通常关系型数据库中获取用户数据进行验证。但是,使用Spring Security可以省去一些验证逻辑的编写:

通常如果你的用户表格,权限表格如果是下面这样,可以直接使用Spring Secuirty中的API来实现验证:

(因为Spring默认查询语句

用户表users

属性 描述
username 用户名
password 密码
enabled 用户身份是否**
….. ….

用户权限表authorities

属性 描述
username 用户名
authority 权限
….. ….

验证逻辑中的API调用还是需要的,如果表格结构是那样的话(不需要严格遵守属性出现顺序),那么重写一些configure方法就好了!


//DI injection
@Autowired
DataSource dataSource;

@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception{
    auth.jdbcAuthentication().dataSource(dataSource);

}

重载默认认证方式

通过代码加注释吧,来解释以下自定义认证方式

//自定义认证方式
@Autowired
DataSource dataSource;
//所有语句都是以username为参数,即'?'占位符
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
    auth.jdbcAuthentication()
    .dataSource(dataSource)
    //链式调用
    //单表查询用户名和密码
    .usersByUsernameQuery("select username,password,activited"
      +"from Item where username=?"
    )
    //选取对应权限为OWNER,注意‘’包围,否则为属性
    .authoritiesByUsernameQuery(
      "select username,'OWNER' from Item where username=?"
    )
    //选取对应实体,组,组权限信息,由于groupName非Spring可识别需要''包围
    .groupAuthoritiesByUsername(
     "select id,'groupName','groupAuthority' from"+
     "Item,MembershipGroup,MemebershipGroupAuthority"+
     "where id=? and"
     "MembershipGroup.id=Item.id and"
     "MemebershipGroupAuthority.id=Item.id"
    );

}

现在,如果你将这些代码合成入WebSecurityConfigurerAdapter,可以实现一个基于
MySQL等数据库的认证。