JavaEE:使用BCrypt加密算法验证登录密码

SpringBoot配置:https://blog.csdn.net/a526001650a/article/details/106687559

1.导入SpringSecurity依赖:

<!-- 导入SrpingSecurity依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2.配置安全类,拦截所有HTTP请求:

//声明为安全配置类,启动微服务时加载
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { //继承WebSecurityConfigurerAdapter,自动加载
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests() //authorizeRequests表示授权
                .antMatchers("/**").permitAll()  //antMatchers("/**")设置拦截所有的请求路径,permitAll为允许所有权限
                .anyRequest() //任何请求
                .authenticated() //认证后允许访问
                .and().csrf().disable(); //三个方法连用让csrf攻击失效
    }
}

3.创建加密/密码比较类,验证登录密码:

(1)在Application中配置创建BCryptPasswordEncoder:

//申明为引导类,类名自定义
@SpringBootApplication
public class JWTApplication {
    ...
    //自动创建Bean对象,类似<bean>中配置
    @Bean
    public BCryptPasswordEncoder bcryptPasswordEncoder(){
        return new BCryptPasswordEncoder();  //Spring自带的BCrypt加密/解密工具类
    }
}

(2)编写加密/密码比较工具类,验证登录密码:

@Service
public class LoginBiz {
    @Autowired
    public BCryptPasswordEncoder bcryptPasswordEncoder; //Spring自带的BCrypt加密/解密工具类,在JWTApplication中创建了对象
    //登录
    public String login(String username, String password) {
        String enPwd = encrypt("123456"); //假如此值从DB中查询的
        if (!match(password, enPwd)) {
            return "登录失败,密码错误";
        }
        return "登录成功";
    }
    //加密
    private String encrypt(String password) {
        return bcryptPasswordEncoder.encode(password); //BCrypt加密
    }
    /**
     * 密码比较
     * @param pwd        原始密码
     * @param encryptPwd 加密后的密码
     * @return true:一样  false:不一样
     */
    public boolean match(String pwd, String encryptPwd) {
        return bcryptPasswordEncoder.matches(pwd, encryptPwd); //比对原始密码和加密后的是否同一个
    }
}

4.测试效果:

(1)配置请求类:

@Controller
public class LoginController {
    @Autowired
    private LoginBiz loginBiz;
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String login(String username, String password) {
        return loginBiz.login(username, password);
    }
}

(2)Postman访问:

username: admin
password: 123456
http://127.0.0.1:10006/login?username=admin&password=123456

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值