spring boot 项目使用 Spring security中的BCryptPasswordEncoder对密码加密与验证

pom.xml

>
	>org.springframework.boot>
	>spring‐boot‐starter‐security>
>

添加一个配置类

在添加spring security依赖后,所有的地址都被spring security所拦截,我们目
前只是需要用到BCrypt密码加密的部分,所以在项目config目录下添加一个配置类,配置为所有地址
都可以匿名访问

package com.ozomall.config;

import org.springframework.context.annotation.Configuration;
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;

/**
 * 安全配置类
 */
@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").permitAll().anyRequest().authenticated().and().csrf().disable();
    }
}

写一个utils类,在service中调用

package com.ozomall.utils;

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

public class Encryption {
    public String encrypt(String pwd) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodePasswod = encoder.encode(pwd);
        return encodePasswod;
    }
}

使用

BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// 加密
String encryptPwd = encryption.encrypt("123456"); // 传入密码
// 对密码进行验证
boolean flag = encoder.matches("123456", encryptPwd); // 传入原密码和加密的后的密码
//flag:true 密码正确;false 密码错误; 

此处登录逻辑

  • 注册时将加密后的密码保存到数据库
  • 登陆时根据账号查出数据库中的密码
  • 将登录接口传过来的密码与数据库中的密码使用encoder.matches方法进行验证

你可能感兴趣的:(spring,boot,spring,boot)