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。
輸入成功就可以跳到設置的首頁