设置登录的用户名和密码
第一种方式:配置文件设置
只需要在spring的appliaction配置文件中设置两个属性
spring.security.user.name=admin
spring.security.user.password=123
第二种方式:配置类
创建一个配置类:
package com.shao.securitydemo01.conif;
import org.springframework.beans.factory.annotation.Autowired;
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;
@Configuration
public class SecurityConif extends WebSecurityConfigurerAdapter {
//创建BCryptPasswordEncoder对象
@Bean
BCryptPasswordEncoder getBCryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//密码加密
String password = bCryptPasswordEncoder.encode("123");
//设置用户名密码和权限
auth.inMemoryAuthentication().withUser("admin").password(password).roles("vip");
}
}
注意:密码必须进行加密!
原因如下:
在 Spring Security 5.0.x 以后,密码的一般格式为:{ID} encodedPassword ,ID 主要用于查找 PasswordEncoder 对应的编码标识符,并且encodedPassword 是所选的原始编码密码 PasswordEncoder。ID 必须书写在密码的前面,开始用{,和 结束 }。如果 ID 找不到,ID 则为null。例如,在相关的源码中,我找到了 Spring Security 定义的不同的编码方式的列表 ID。所有原始密码都是“ password ”。
第三种方式:自定义实现类
第一步: 自定义类实现UserDatailsService接口,设置用户名和密码
//自定义类实现UserDatailsService接口
@Service
public class MyUserServiceDetail implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//获取权限列表
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("vip");
//返回User对象
return new User("admin",new BCryptPasswordEncoder().encode("1231"),auths);
}
}
第二步: 修改配置类,在配置了中指定使用自定义类实现认证
@Configuration
public class SecurityConif1 extends WebSecurityConfigurerAdapter {
//注入自定类
@Autowired
private MyUserServiceDetail myUserServiceDetail;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*
如果有配置文件则使用配置文件的配置用户名和密码
如果没有配置文件则使用配置类里的文件
*/
auth.userDetailsService(myUserServiceDetail).passwordEncoder(getPasswordEncoder());
}
@Bean
PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
连接数据库实现认证
第一步:编写自定义类实现UserDatilsService接口:
@Service
public class MyUserServiceDetail implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*
调用Dao层查询数据库
*/
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
Users user = usersMapper.selectOne(wrapper);
if (user == null){
throw new UsernameNotFoundException("用户名不存在!");
}
//获取权限列表
List<GrantedAuthority> auths = AuthorityUtils.createAuthorityList("vip");
//返回User对象,通过实体类进行获取User中的属性
return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),auths);
}
}
第二步:编写配置类,使用自定义类实现认证功能:
@Configuration
public class SecurityConif1 extends WebSecurityConfigurerAdapter {
//注入自定类
@Autowired
private MyUserServiceDetail myUserServiceDetail;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*
如果有配置文件则使用配置文件的配置用户名和密码
如果没有配置文件则使用配置类里的文件
*/
auth.userDetailsService(myUserServiceDetail).passwordEncoder(getPasswordEncoder());
}
@Bean
PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
登录页面等设置
在继承WebSecurityConfigurerAdapter的配置类中重写configure(HttpSecurity http)方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()//开启自定义登录功能
.loginPage("/login.html")//登录页面
.loginProcessingUrl("/user/login")//登录页面要访问的Controller,这里是访问Security中的.
.defaultSuccessUrl("/test/hello").permitAll()//登录成功后默认访问页面
.and()
.authorizeRequests()
.antMatchers("/test/index","/user/login").permitAll()//这些请求不走过滤器
.anyRequest().authenticated()//其他的要走过滤器
.and()
.csrf().disable();//关闭csrf防护
}