<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/l1/**").hasRole("vip1")
.antMatchers("/l2/**").hasRole("vip2")
.antMatchers("/l3/**").hasRole("vip3");
http.formLogin();
http.logout().logoutSuccessUrl("/");
http.rememberMe().rememberMeParameter("remember");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zs").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3")
.and()
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");
}
}
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4
<div sec:authorize="!isAuthenticated()">显示未认证内容</div>
<div sec:authorize="isAuthenticated()">显示认证内容</div>
<span sec:authentication="name"></span>
<span sec:authentication="principal.authorities"></span>
<div sec:authorize="hasRole('VIP1')"></div>