http://learn.lianglianglee.com/

02 用户认证:如何使用 Spring Security 构建用户认证体系?

image.png

用户名密码如何传递?

两种方法传递用户名密码(或者token):

http基础认证:

请求头部添加Authorization: ,这里的 type 就是“Basic”,而 credentials 则是这样一个字符串:

dXNlcjo5YjE5MWMwNC1lNWMzLTQ0YzctOGE3ZS0yNWNkMjY3MmVmMzk=

这个字符串就是将用户名和密码组合在一起,再经过 Base64 编码得到的结果

表单登录

Spring Security 学习 - 图2


开启方法:继承WebSecurityConfigurerAdapter 类,并重写configure(HttpSecurity http)方法

  1. //开启httpBasic
  2. protected void configure(HttpSecurity http) throws Exception {
  3. http.httpBasic();
  4. }
  5. //开启表单登录
  6. protected void configure(HttpSecurity http) throws Exception {
  7. http.formLogin();
  8. }

如何验证用户身份?

yml配置文件配置用户名密码进行校对

spring:

  security:

    user:

      name: spring

      password: spring_password

使用基于内存的用户信息存储方案

重写configure(AuthenticationManagerBuilder builder)方法,设定用户名、密码、角色。

@Override

protected void configure(AuthenticationManagerBuilder builder) throws Exception {



    builder.inMemoryAuthentication()

        .withUser("spring_user").password("password1").roles("USER")

        .and()

        .withUser("spring_admin").password("password2").roles("USER", "ADMIN");

}

注意:roles()方法直接传递角色名即可,**authorities() **需要传递ROLE_加角色名。

@Override

protected void configure(AuthenticationManagerBuilder builder) throws Exception {



    builder.inMemoryAuthentication()

         .withUser("spring_user").password("password1").authorities("ROLE_USER")

         .and()

         .withUser("spring_admin").password("password2").authorities("ROLE_USER", "ROLE_ADMIN");

}

使用基于数据库的用户信息存储方案

具体可以看:https://www.baeldung.com/spring-security-jdbc-authentication

表结构:

create table users(username varchar_ignorecase(50) not null primary key,password varchar_ignorecase(500) not null,enabled boolean not null);



create table authorities (username varchar_ignorecase(50) not null,authority varchar_ignorecase(50) not null,constraint fk_authorities_users foreign key(username) references users(username));



create unique index ix_auth_username on authorities (username,authority);

开启Spring SecurityJDBC配置:

@Autowired

DataSource dataSource;



@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {



        auth.jdbcAuthentication().dataSource(dataSource)

               .usersByUsernameQuery("select username, password, enabled from Users " + "where username=?")

               .authoritiesByUsernameQuery("select username, authority from UserAuthorities " + "where username=?")

               .passwordEncoder(new BCryptPasswordEncoder());

}