Spring Security 简单示例
程序员文章站
2022-05-25 11:54:05
...
Spring security 默认开启 csrf ,post 提交需要提供 csrf token
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
注销的处理逻辑:
The default is that accessing the URL "/logout" will log the user out by invalidating the HTTP Session, cleaning up any rememberMe() authentication that was configured, clearing the SecurityContextHolder,
and then redirect to "/login?success".
注意:如果开启 csrf ,注销需要使用 post 提交
定义视图映射:
本例中的登陆页面由 Spring 默认提供
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/greet").setViewName("greet");
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h1>Welcome!</h1>
<p>
Click <a href="/greet">here</a> to see a greeting.
</p>
</body>
</html>
greet.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello world!</title>
</head>
<body>
<h1>Hello world!</h1>
<p>
<form action="/logout" method="post">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<input type="submit" value="Sign Out" />
</form>
</p>
</body>
</html>
继承 WebSecurityConfigurerAdapter 定制安全策略
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/") // 匹配请求路径 '/'
.permitAll() // 允许未认证用户访问
.anyRequest() // 所有的请求(排除掉上面放行的)
.authenticated() // 通过认证的任意角色用户可以访问
.and() // 返回 HttpSecurity
.formLogin() // 配置通过登录页面进行认证,默认映射为 /login, Spring boot 也会提供一个默认页面
.permitAll() // 允许未认证用户访问 /login
.and() // 返回 HttpSecurity
.logout() // 配置注销,默认映射为 /logout
.permitAll(); // 允许未认证用户访问 /logout
}
@Autowired // 注入全局的 AuthenticationManagerBuilder, 如果使用 @Override 则会新建一个 AuthenticationManager 实例
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication() // 使用基于内存的 AuthenticationProvider
.withUser("user").password("123321").roles("USER"); // 构建一个 User 给 userDetailsManager, 而该类继承于 UserDetailsService
}
}
更复杂的示例,请看:security-customize