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