Spring Security的web权限控制方案 · 认证
一、认证的基础三种方式
(一)设置登录的用户名和密码
1.通过配置文件
在application.properties中,写上如下代码,即可设置用户名为tom,密码为123
#spring.security.user.name=tom
#spring.security.user.password=123
加入用户名和密码后,就不会在控制台自动生成密码,在登录界面,输入自定义的用户名tom和密码123即可访问成功
2.通过配置类
创建config包,创建SecurityConfig继承WebSecurityConfigurerAdapter,重写 protected void configure(AuthenticationManagerBuilder auth) ()方法
但是当如上图写好进行访问时,会出现如下报错,且浏览器页面没有反应
There is no PasswordEncoder mapped for the id “null”
表示PasswordEncoder匹配的id值为空,因为密码是进行加密过的,需要找寻PasswordEncoder对象解密,而默认是没有的。因此,解决办法就是配置出来,但是因为是一个借口,所以要new出来一个该接口的实现类:
package com.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 配置类,配置登录的用户名和密码,密码进行加密
* 用户名:jack
* 密码:123
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//将密码进行加密
BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
String password = passwordEncoder.encode("123");
//System.out.println(password);
//设置登录信息
auth.inMemoryAuthentication()