使用Spring Security对密码进行加密

首先要确保项目已经引入了Spring Security的依赖,如果没有,可以在pom.xml添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

创建 BCryptPasswordEncoder 的 Bean

在配置类,添加如下代码:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class SecurityConfig {

    /**
     * 配置密码加密器
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 放行接口配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable() // 关闭 csrf(你是前后端分离项目一般要关)
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(
                    "/user/login", 
                    "/user/register", 
                    "/swagger-ui/**", 
                    "/v3/api-docs/**", 
                    "/favicon.ico"
                ).permitAll() // 放行这些接口
                .anyRequest().permitAll() // 如果你还没有登录控制,可全部放行(后期记得改为 .authenticated())
            )
            .formLogin().disable() // 禁用默认登录页面
            .httpBasic().disable(); // 禁用 basic auth

        return http.build();
    }
}


然后就可以在service中注入使用

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Service
public class TeamServiceImpl implements TeamService {

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    // 然后你就可以直接用:
    // String encodedPassword = passwordEncoder.encode(team.getPassword());
}

需要注意的是,加密后密码是无法解密的,只能在校验时通过 passwordEncoder.matches(raw, encoded) 判断是否匹配。因此在校验加入队伍密码时也应该使用 matches 方法进行比对。

// 关键:使用 matches 方法校验
    if (pwd == null || !passwordEncoder.matches(pwd, team.getPassword())) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码错误");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值