表单登录
Spring Security 表单登录
Form Login | 用户名密码表单登录
本部分完整代码参考 spring-security-form-login, 首先在 WebSecurityConfig 的 configure 方法中,注册路由表:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
然后需要声明 UserDetailsService,以供 Spring Context 来自动获取用户实例,该方法会在 authenticationManager.authenticate()
调用时被调用:
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
此时 Spring Security 为我们自动生成了 /login
与 /logout
两个 POST 接口,分别用来处理用户登录与登出,其对应的前台 Form 表单如下所示:
<form th:action="@{/login}" method="post">
<div>
<label> User Name : <input type="text" name="username" /> </label>
</div>
<div>
<label> Password: <input type="password" name="password" /> </label>
</div>
<div><input type="submit" value="Sign In" /></div>
</form>
在很多情况下,我们位于第三方存储中的密码是经过 Hash 混淆处理的,而不是直接读取的明文信息;此时我们可以为 Spring Security 提供自定义的密码编码器,来方便其执行比较操作:
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}