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 提供存储在内存中的基于用户名/密码的身份验证支持。

修改 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 在内部给我们做了变换,感兴趣的可以看看源码。

在这里插入图片描述

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

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

在这里插入图片描述

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

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

在这里插入图片描述

参考

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

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

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security是一个功能强大的框架,用于在Spring Boot应用程序实现用户认证和授权管理。以下是实现用户认证的一般步骤: 1. 添加Spring Security依赖:在项目的pom.xml文件添加Spring Security的依赖项。 2. 创建用户实体类:创建一个用户实体类,用于存储用户的身份验证信息,例如用户名和密码。 3. 创建用户存储库:创建一个用户存储库接口,用于从数据库或其他数据源检索用户信息。 4. 实现用户服务:创建一个用户服务类,实现UserDetailsService接口,并重写loadUserByUsername方法,用于根据用户名从用户存储库获取用户信息。 5. 配置Spring Security:创建一个配置类,继承WebSecurityConfigurerAdapter,并重写configure方法,用于配置Spring Security的行为。 6. 配置用户认证:在configure方法,使用AuthenticationManagerBuilder配置用户认证方式,例如使用内存存储、数据库存储或自定义认证方式。 7. 配置登录页面:在configure方法,使用formLogin方法配置登录页面的URL和登录成功后的跳转URL。 8. 配置访问控制:在configure方法,使用authorizeRequests方法配置不同URL路径的访问权限,例如需要认证才能访问的URL和不需要认证的URL。 9. 实现自定义登录页面:如果需要自定义登录页面,可以创建一个登录页面的控制器,并在configure方法使用loginPage方法配置自定义登录页面的URL。 10. 实现自定义认证成功处理器:如果需要在认证成功后执行一些自定义操作,可以创建一个认证成功处理器,并在configure方法使用successHandler方法配置自定义认证成功处理器。 11. 实现自定义认证失败处理器:如果需要在认证失败后执行一些自定义操作,可以创建一个认证失败处理器,并在configure方法使用failureHandler方法配置自定义认证失败处理器。 以下是一个示例代码,演示了如何使用Spring Security实现用户认证: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home") .permitAll() .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login") .permitAll(); } } ``` 请注意,上述代码只是一个示例,实际的配置可能因应用程序的需求而有所不同。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值