1.第一种,直接在yml文件中进行设置
2.第二种,直接在内存中匹配用户名和密码
首先我们要创建一个Sercurity的配置类,在配置类中实现config方法方法,
package com.example.sercurity.config;
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;
@Configuration
public class SercurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//采用 BCryptPasswordEncoder方法对密码进行加密
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder ( );
String encode = encoder.encode ( "123456" );
//inMemoryAuthentication方法是对用户登录进行请求认证
auth.inMemoryAuthentication ().withUser ( "admin" ).password ( encode ).roles ( "vip1" );
//super.configure ( auth );
}
}
此时运行,当你输入账号密码时后报错,因为缺少一个PasswordEncoder对象,错误如下:
此时我们需要创建一个能返回PasswordEncoder对象的Bean类
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
3.第三种,通过已定义的配置类连接数据库进行认证
具体请看此博客