Spring Security httpbasic的三种密码认证方式

博客介绍了Spring Security httpbasic的三种密码认证方式。一是在内存中指定密码,适用于演示和测试;二是使用密码编码器对密码进行安全编码;三是使用数据库存储密码,需实现UserDetailsService接口从数据库加载用户信息和密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring Security httpbasic的三种密码认证方式

在 Spring Security 中,可以通过多种方式指定密码。以下是几种常见的方式:

认证一—— 在内存中指定密码


@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("tom")
                .password("{noop}123456") // 指定密码,{noop} 表示密码以明文形式存储
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

使用 withUser() 方法指定用户名,使用 password() 方法指定密码。{noop} 前缀表示密码以明文形式存储,仅适用于演示和测试目的。在生产环境中,应该使用适当的密码编码方式。

认证二—— 使用密码编码器(PasswordEncoder)

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private PasswordEncoder passwordEncoder;
    @Autowired
    public void setPasswordEncoder() {
        this.passwordEncoder = new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("tom")
                .password(passwordEncoder.encode("123456"))
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }

通过使用密码编码器(PasswordEncoder),可以对密码进行安全的编码。你可以选择合适的密码编码器实现,例如 BCryptPasswordEncoder、StandardPasswordEncoder、MessageDigestPasswordEncoder 等。需要确保密码编码器的实例已经配置好,并通过 @Autowired 注入到配置类中。

认证三——使用数据库存储密码

spring security 配置类

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * 通过使用 UserDetailsService 来加载用户信息,可以从数据库或其他存储中获取用户的密码。
     * 你需要实现 UserDetailsService 接口,并根据实际情况从数据库中加载用户信息和密码。
     */
    @Autowired
    private CustomDetailsService customDetailsService;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }


自定义 UserDetailsService

@Service
public class CustomDetailsService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中根据用户名加载用户信息
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found"));
        System.out.println("user=" + user);
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .roles(user.getRoles())
                .build();
    }

查询用户密码类

@Repository
public class UserRepository {
    public Optional<User> findByUsername(String userName) throws UsernameNotFoundException{
        //TODO
        //查询数据库用户信息 ....
        //tom  123456 admin
        return Optional.of(new User("tom","$2a$10$WHv0jAVrVAwde6PaSgD6AeY6MkjweHav1mPm0urIvw4fBnBjfTWau","admin"));
    }
}

自定义user

@Data
@ToString
@AllArgsConstructor
public class User {
    private String username;
    private String password;
    private String roles;

}

使用 UserDetailsService 来加载用户信息,可以从数据库或其他存储中获取用户的密码。你需要实现 UserDetailsService 接口,并根据实际情况从数据库中加载用户信息和密码。

controller类

@RestController
@RequestMapping("/demo")
public class DemoController {
    @RequestMapping("/hello")
    @ResponseBody
    public String hello(){
        return "hello word";
    }
}

依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!--添加web依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--添加热部署依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!--添加lombok 依赖 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
<!--        &lt;!&ndash;添加mp 依赖 &ndash;&gt;
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>-->
        <!--添加Spring Security 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

验证在auth中进行验证

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值