Spring Security - 07 在内存中认证(添加用户到内存中)

文章目录

  • 环境
  • 项目结构
  • 添加用户到内存中
  • 测试
  • 参考

环境

操作系统:

Windows 10 x64

集成开发环境:

Spring Tool Suite 4 
Version: 4.12.1.RELEASE
Build Id: 202110260750

浏览器(客户端):

Google Chrome
版本 97.0.4692.71(正式版本) (64 位)
Firefox Browser
96.0.3 (64 位)
Microsoft Edge
版本 98.0.1108.43 (官方内部版本) (64 位)

项目结构

参考:Spring Security - 06 修改默认的用户名和密码

Spring Security - 07 在内存中认证(添加用户到内存中)_第1张图片

添加用户到内存中

Spring Security 提供存储在内存中的基于用户名/密码的身份验证支持。

修改 WebSecurityConfigurer 配置类,重写 configure(AuthenticationManagerBuilder) 方法(第 27 ~ 139 行):

备注:这里总共用了四种方式(也可以说是三种,因为第三、四种方式的区别在于前者是基于 UserDetails 接口,后者是直接使用 UserDetails 接口的 User 子类),将四个用户添加到内存中。看似很复杂,其实很简单!

package com.mk.security.config.annotation.web.configuration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;

//@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        { // 方式一
            String username = "zhangsan";
            String password = passwordEncoder.encode("123");
            String[] roles = { "USER" }; // 此用户拥有的角色
            
            auth.inMemoryAuthentication()
                    .withUser(username)
                    .password(password)
                    .roles(roles);
        }
        
        { // 方式二
            String username = "lisi";
            String password = "123";
            List<GrantedAuthority> authorities = new ArrayList<>();
            // 此用户拥有的权限,如果把角色比喻成集合,那么权限就是该集合(角色)中的元素
            authorities.add(new SimpleGrantedAuthority("USER:CREATE"));
            authorities.add(new SimpleGrantedAuthority("USER:RETRIEVE"));
            authorities.add(new SimpleGrantedAuthority("USER:UPDATE"));
            authorities.add(new SimpleGrantedAuthority("USER:DELETE"));
            
            UserBuilder userBuilder = User.builder()
                    .passwordEncoder(raw -> passwordEncoder.encode(raw))
                    .username(username)
                    .password(password)
                    .disabled(false)
                    .accountExpired(false)
                    .credentialsExpired(false)
                    .accountLocked(false)
                    .authorities(authorities);
            
            auth.inMemoryAuthentication().withUser(userBuilder);
        }
        
        { // 方式三
            UserDetails userDetails = new UserDetails() {
                
                private static final long serialVersionUID = 1L;
                
                private String username = "wangwu";
                private String password = passwordEncoder.encode("123");
                
                
                @Override
                public boolean isEnabled() {
                    return true;
                }
                
                @Override
                public boolean isCredentialsNonExpired() {
                    return true;
                }
                
                @Override
                public boolean isAccountNonLocked() {
                    return true;
                }
                
                @Override
                public boolean isAccountNonExpired() {
                    return true;
                }
                
                @Override
                public String getUsername() {
                    return username;
                }
                
                @Override
                public String getPassword() {
                    return password;
                }
                
                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    List<GrantedAuthority> authorities = new ArrayList<>();
                    
                    authorities.add(new SimpleGrantedAuthority("USER:CREATE"));
                    authorities.add(new SimpleGrantedAuthority("USER:RETRIEVE"));
                    authorities.add(new SimpleGrantedAuthority("USER:UPDATE"));
                    authorities.add(new SimpleGrantedAuthority("USER:DELETE"));
                    
                    return authorities;
                }
            };
            
            auth.inMemoryAuthentication().withUser(userDetails);
        }
        
        { // 方式四
            String username = "zhaoliu";
            String password = passwordEncoder.encode("123");
            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            List<GrantedAuthority> authorities = new ArrayList<>();
            
            authorities.add(new SimpleGrantedAuthority("USER:CREATE"));
            authorities.add(new SimpleGrantedAuthority("USER:RETRIEVE"));
            authorities.add(new SimpleGrantedAuthority("USER:UPDATE"));
            authorities.add(new SimpleGrantedAuthority("USER:DELETE"));
            
            User user = new User(username, password, 
                    enabled, accountNonExpired, 
                    credentialsNonExpired, accountNonLocked, 
                    authorities);
            
            auth.inMemoryAuthentication().withUser(user);
        }
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());
//        http.authorizeRequests().anyRequest().authenticated();
    }
}

新建 PasswordEncoderConfiguration 配置类,提供一个密码编码器,用于密码加密:

package com.mk.security.crypto.password;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class PasswordEncoderConfiguration {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

测试

启动项目,打开谷歌浏览器,如果你已经登录,请先退出登录,防止遗留的认证信息干扰本次测试。

注意:当我们将用户添加到内存之后,默认的用户名和密码就不可用了!

访问 http://localhost:8080/principal,Spring Security 将我们重定向至 http://localhost:8080/login,让我们使用 zhangsan 用户登录:

注意:为什么我们给 zhangsan 用户分配的角色是 USER,而这里却变成 ROLE_USER 权限呢?这是 Spring Security 在内部给我们做了变换,感兴趣的可以看看源码。

Spring Security - 07 在内存中认证(添加用户到内存中)_第2张图片

打开火狐浏览器,如果你已经登录,请先退出登录,防止遗留的认证信息干扰本次测试。

访问 http://localhost:8080/principal,Spring Security 将我们重定向至 http://localhost:8080/login,让我们使用 lisi 用户登录:

Spring Security - 07 在内存中认证(添加用户到内存中)_第3张图片

打开 Edge 浏览器,如果你已经登录,请先退出登录,防止遗留的认证信息干扰本次测试。

访问 http://localhost:8080/principal,Spring Security 将我们重定向至 http://localhost:8080/login,让我们使用 wangwu 用户登录:

Spring Security - 07 在内存中认证(添加用户到内存中)_第4张图片

参考

Spring Security / Servlet Applications / Authentication / Username/Password / Password Storage / In Memory / In-Memory Authentication

Spring Security / Features / Authentication / Password Storage / Password Storage

探索Java8:(二)Function接口的使用

你可能感兴趣的:(Spring,Security,spring,java,spring,security)