- 所需依赖
springboot 版本要为为2.0.7 不然thymeleaf中security标签无效
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 自定义security配置 SecurityConfig .class
/**
* 启用自定义Spring Security配置
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 注意:authorities() roles()都可以进行身份认证
* .authorities("ADMIN") .hasAuthority("ADMIN") {"authority":"ADMIN"}
* .roles("USER") .hasRole("USER") {"authority":"ROLE_USER"}
* .authorities("ROLE_ADMIN") .hasAuthority("ROLE_ADMIN") {"authority":"ROLE_USER"}
* .roles("ROLE_USER") .hasRole("ROLE_USER") 不允许前面加ROLE_ 会报错
*/
@Override // 认证
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中配置用户,配置多个用户调用`and()`方法
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder()) // 指定加密方式
.withUser("admin").password(passwordEncoder().encode("123456")).authorities("ROLE_ADMIN")
.and()
.withUser("test").password(passwordEncoder().encode("123456")).roles("USER");
}
@Override // 授权:为特定网页设置权限,拥有权限的用户才能进行访问此页面
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll() // 任何角色都可以访问根路径,该路径不需要用户进行登入,其他都要
.antMatchers("/login1","/formlogin","/outlog").permitAll()
.antMatchers("/hello").hasAuthority("ROLE_ADMIN")
.antMatchers("/hello1").hasRole("USER")
.anyRequest().authenticated() // 除了上述除外的路径,其他路径全需要登入认证
;
// HttpSessionCsrfTokenRepository
http.formLogin().loginPage("/login1").loginProcessingUrl("/formlogin"); // 默认使用security自带登入页面进行登入z
// 将csrf保护关闭后,logoutUrl能设置Http任何请求退出
// http.csrf().disable();
// 默认下csrf是开启的,logoutUrl必须是默认的/logout才能退出
http.logout() // 默认退出路径 /logout
// .logoutUrl("/outlog") // csrf保护关闭后,才能通过Get方式进行登出
// csrf开启下配置,页面需要带上token值,通过token值进行自定义的用户登入退出,自定义退出路径为任意方式退出,get,post。。。
.logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST")).permitAll()
.logoutSuccessUrl("/") // 退出成功后调整至 /
.invalidateHttpSession(true) // 是否删除session
.deleteCookies("JSESSIONID") // 删除cookie中JSESSIONID值
;
}
@Bean
public PasswordEncoder passwordEncoder() {
// BCryptPasswordEncoder:Spring Security 提供的加密工具,可快速实现加密加盐
return new BCryptPasswordEncoder();
}
}
- 前端页面导入标签库
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4" >
</html>
- 用例
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<!--判断用户是否登入,登入显示欢迎-->
<div sec:authorize="isAuthenticated()">
欢迎登入系统
</div>
<!--判读用户权限是否是ADMIN-->
<div sec:authorize="hasRole('ADMIN')">
欢迎拥有ADMIN权限用户登入网站
</div>
<!--显示登入用户名称-->
<div sec:authentication="name"></div>
<!--判断用户是否拥有访问sec:authorize-url 路径的权限,若无权限链接不显示-->
<a href="/hello" sec:authorize-url="/hello">hello</a>
<a href="/hello1" sec:authorize-url="/hello1">hello1</a>
<form action="/formlogin" method="post">
用户名:<input type="text" name="username" >
密码:<input type="password" name="password">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
<input type="submit" value="登入">
</form>
<form method="post" action="/outlog">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
<input type="submit" value="退出">
</form>
</body>
</html>
在session中取得spring security的登录用户名如下
${session.SPRING_SECURITY_CONTEXT.authentication.principal.username}
注意
在使用安全框架允许csrf保护时,除了Get方法不会被框架拦截,其他Post,Put,Delete方法都会被拦截,要想不被拦截,需要在发送的表单
或者ajax
中添加token值,才允许请求执行
一 . 在表达中提交token.
例:
<form action="/post" method="post">
用户名:<input type="text" name="username" >
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
<input type="submit" value="登入">
</form>
二 . 在头部添加token
2.然后在ajax添加请求头
添加token头和token值
自定义记住我
功能
http.rememberMe(); // 开启记住我功能
<form action="/formlogin" method="post">
用户名:<input type="text" name="username" >
密码:<input type="password" name="password">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
<!--表单参数中添加remember-me属性,用于记住我功能开启-->
<p>
<label>Remember Me</label>
<input type="checkbox" th:name="remember-me">
</p>
<input type="submit" value="登入">
</form>
Spring Boot + Spring Security + Thymeleaf 简单教程
thymeleaf使用security,github详细文档