Spring Security 简单示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值