设置登录系统的账号、密码三种方式
方式一:在 application.properties
spring.security.user.name=cxy
spring.security.user.password=cxy
方式二:编写类实现接口
//@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
String password = passwordEncoder.encode("123");
auth.inMemoryAuthentication().withUser("lucy").password(password).roles("admin");
}
//手动写上,不然报错
//java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
}
方式三:自定义方法(用户名和密码从数据库中获取)
//自定义配置类:用户名和密码获取
@Configuration
public class SecurityConfigDatail extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDatailService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDatailService).passwordEncoder(password());
}
//手动写上,不然报错
//java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
@Bean
PasswordEncoder password() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//配置没有权限访问自定义跳转页面
http.exceptionHandling().accessDeniedPage("/unauth.html");
http.formLogin() //定义自己编写的登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index").permitAll() //登录成功之后,跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/login").permitAll() //这些路径不需要访问就可以直接进入
//当前登录用户,只有具有admins权限才可以访问这个路径
//1.hasAuthority这个权限适用于一个用户只有一个权限
// .antMatchers("/test/index").hasAuthority("admins")
//2.hasAnyAuthority这个权限适用于一个用户有多个权限
// .antMatchers("/test/index").hasAnyAuthority("admins,manager")
//3.hasRole ROLE_sale
// .antMatchers("/test/index").hasRole("sale")
//4.hasAnyRole 用户具备其中一个就可以操作
.antMatchers("/test/index").hasAnyRole("sale,abc")
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf防护
}
}
service层:
@Service("userDatailService")
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
//调用方法查询数据库
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username",s);
Users users = usersMapper.selectOne(wrapper);
//判断
if(users == null){//数据库没有数据,认证失败
throw new UsernameNotFoundException("用户名不存在");
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);
}
}
userMapper:
import com.atguigu.securitydemo1.entiy.Users;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}
user:
import lombok.Data;
@Data
public class Users {
private Integer id;
private String username;
private String password;
}
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/user/login">
用户名:<input type="text" name="username">
<br/>
密码:<input type="text" name="password">
<br/>
<input type="submit" value="login">
</form>
</body>
</html>
使用的时候需要配置:
1.在启动类上加上@MapperScan(“com.cxy.securitydemo.mapper”)
2.使用mp需要加入依赖:
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!--lombok用来简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
3.application.properties中配置数据库地址