整合Spring Security
整合方法
-
创建项目时选择security依赖或在pom中添加security依赖
-
建立
SpringSecurityConfig
类,继承WebSecurityConfigurerAdapter
方法 -
在刚刚创建的类上添加
@EnableWebSecurity
注解 -
设置授权规则
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/").permitAll() //所有人均可访问 .antMatchers("/level1/**").hasRole("vip1") //vip1可访问 .antMatchers("/level2/**").hasRole("vip2") //vip3可访问 .antMatchers("/level3/**").hasRole("vip3"); //vip3可访问 http.formLogin() //启动security自带login页面 .loginPage("/toLogin") //设置自定义login页面 .loginProcessingUrl("/login") //设置自定义login认证页面 .usernameParameter("user") //设置login页面中的账户参数名 .passwordParameter("pwd"); //设置login页面中的密码参数名 http.logout() //logout:添加登出页面 .logoutSuccessUrl("/"); //logoutSuccessUrl:添加登出后跳转页面 http.rememberMe() //开启记住我功能 .rememberMeParameter("rem"); //设置记住我参数名 }
-
设置角色
@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("shimeath").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); }
Spring security整合thymeleaf
-
添加maven依赖
<dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> </dependency>
2.添加命名空间
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
-
常用方法
sec:authorize <!-- 授权 --> sec:authentication <!-- 认证方式 --> <!-- 函数 --> isAuthenticated() <!-- 已登录吗 --> hasRole('vip1') <!-- 判断角色 -->