Spring Boot Security自定义用户认证逻辑
目录
1、实现WebSecurityConfigurerAdapter虚拟类,
2、实现接口UserDetailsService类:MyUserDetailsService
1、实现WebSecurityConfigurerAdapter虚拟类,
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/* @Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
System.out.println("哈哈哈");
auth.inMemoryAuthentication().withUser("user")
.password("user").roles("USER").and()
.withUser("admin")
.password("admin")
.roles("USER","ADMIN");
}*/
@Override
protected void configure(HttpSecurity http) throws Exception{
http.formLogin()
.loginPage("/login")
.loginProcessingUrl("/user/login")
.and()
.authorizeRequests()
.antMatchers("/login")
.permitAll()
.anyRequest()
.authenticated()
.and()
.logout()
.logoutUrl("/login/index")
.and()
.csrf().disable()
;
}
}
其中passwordEncoder()方法是下面MyUserDetailsService中使用到的;configure(HttpSecurity http)方法里实现了登录页面,登录成功跳转的页面等等。
2、实现接口UserDetailsService类:MyUserDetailsService
@Component
public class MyUserDetailsService implements UserDetailsService
{
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String password =passwordEncoder.encode("123456");
System.out.println("密码:"+password);
User user = new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
return user;
}
}
loadUserByUsername方法返回一个包含用户名和密码的的Security一个User类对象。
3、登录页的控制器
@Controller
@RequestMapping("login")
public class LoginController {
@GetMapping()
private String login(){
return "login";
}
@GetMapping("index")
private String index(){
return "index";
}
}
4、登录页的HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录页面</title>
</head>
<body>
<h2>自定义登录页面</h2>
<form action="/user/login" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2"><button type="submit">登录</button></td>
</tr>
</table>
</form>
</body>
</html>
5、效果:启动项目,在浏览器输入你的地址。会自动跳到登录页
在登录页面如果任意一个用户名(因为没有校验用户名,任意一个用户名就可以),和密码123456。
输入成功就可以跳到设置的首页