SpringSecurity5 自定义登陆、登出等接口

回到序章

来来来,点这

正文

注: 其实这个更多是让你在玩前后分离时配置的,不过因为我懒,所以就将就将就吧。

继续沿用初体验里的配置类,要自定义表单登陆里的接口,就只需要重写父类中的 configure(HttpSecurity http) 实现,常用的配置代码及解释如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin1").password("{noop}123").roles("admin");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 配置权限
.authorizeRequests()
// 配置任意请求都需要登陆
.anyRequest().authenticated()
.and()
// 开启 formLogin 默认配置
.formLogin()
// 请求时未登陆跳转的页面
.loginPage("/login/auth").permitAll() // .permitAll() 配置任何人都可以访问
// 账号密码错误跳转的页面
.failureUrl("/login/fail")
// 默认的登陆成功跳转页面,如果每次登陆成功后都想要强行跳转到这,第二个参数改成 true 即可,不设置默认为 false
.defaultSuccessUrl("/login/success", false)
// 登陆接口, post
.loginProcessingUrl("/login")
// 认证的账号参数 key 值
.usernameParameter("username")
// 认证的密码参数 key 值
.passwordParameter("password")
.and()
// 登出配置
.logout()
// 登出接口
.logoutUrl("/logout")
// 注销成功跳转接口
.logoutSuccessUrl("/login/logout").permitAll() // .permitAll() 配置任何人都可以访问
// 删除自己创建的 cookie,没有则不搭理
.deleteCookies("myCookie")
.and()
// 禁用 csrf,默认开启,防止跨站伪造请求
.csrf().disable();
}
}