1. 授权
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
意为对应页面,所授权的角色
2. 认证
账号密码,以及所授权是角色
3. 简单指令
sec:authentication="name"
获取当前角色名
!isAuthenticated()
未登录显示按钮
<div sec:authorize="!isAuthenticated()">
<!--未登录-->
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
</div>
isAuthenticated()
已登录显示按钮
<div sec:authorize="isAuthenticated()">
<!--已登录-->
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
4. 账户拥有该角色,显示该角色下的功能
hasRole('')值,与之对应即可
SecurityConfig类代码
package cn.hm1006.config;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
//排除拦截的页面 首页所有人皆可访问
.antMatchers("/").permitAll()
//拦截的页面,增加角色访问 功能页拥有对应权限的人才能访问
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限,开启默认进入登录页面
http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/dologin");
//注销 /logout 配置注销后进入到首页
http.logout().logoutSuccessUrl("/");
http.csrf().disable();//关闭csrf功能
//开启记住我功能
http.rememberMe().rememberMeParameter("remeberMe");
}
//认证
@Override
public void configure(AuthenticationManagerBuilder auto) throws Exception {
//正常情况这些数据需要从数据库读取 密码编码PasswordEncoder
auto.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("vip1","vip2","vip3")
.and()
.withUser("test").password(new BCryptPasswordEncoder().encode("test")).roles("vip1");
}
}
Q.E.D.