1.简介
最近在学习SpringSecurity安全框架,在这里对所学的知识,以及遇见问题进行总结。
2.maven引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
3.不做任何配置直接运行项目,他会有默认的登陆页面以及随机的登陆密码
4.目录结构
5.登陆页面
<form action="/login" method="post">
<label for="name">用户名:<input type="text" id="name" name="username" value="admin"></label>
<label for="pass">密码:<input type="text" id="pass" name="password" value="123456"></label>
<input type="submit" value="登陆">
</form>
6.loginController.java
@RestController
public class LoginController {
@RequestMapping("succ")
public String succ(){
return "index.html";
}
@RequestMapping("fail")
public String fail(){
return "fail.html";
}
}
7.配置自己的登陆页面
继承WebSecurityConfigurerAdapter 类
重写configure(HttpSecurity http) 方法
.csrf().disable()必须加不然会包302错误,会一直重定向登陆页面
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//方向页面或接口
.antMatchers("/login.html").permitAll()
.antMatchers("/fail.html").permitAll().
//所有页面都必须认证登陆
.anyRequest().authenticated()
.and()
.formLogin()
//自定义登陆界面
.loginPage("/login.html")
//页面登陆时跳转的登陆方法、和我自己写的Controller没有关系
//必须和表单的action="/login" 地址一样
//自定义登陆逻辑 登陆时走这个路口
.loginProcessingUrl("/login")
//成功跳转 必须是post方式
.successForwardUrl("/succ")
//失败跳转 必须是post方式
.failureForwardUrl("/fail")
//自定义登陆参数
//.usernameParameter("")
//.passwordParameter("");
.and()
//关闭srf防护
.csrf().disable();
}
@Bean
public PasswordEncoder pw(){
return new BCryptPasswordEncoder();
}
8.更改登陆逻辑
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
private PasswordEncoder pw;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("sdafdsfsadfsafdsd");
//1.根据username查询数据库
if(!"admin".equals(username)){
throw new UsernameNotFoundException("用户名或密码错误");
}
//2.根据查询的对象比较密码
String password = pw.encode("123456");
//3.返回用户对象
return new User("admin",password, AuthorityUtils
.commaSeparatedStringToAuthorityList("admin,aa"));
}
}