- 1 依赖
- 2 MySecurityConfig
- 3 权限控制
2 MySecurityConfigorg.springframework.boot spring-boot-starter-securityorg.springframework.boot spring-boot-starter-weborg.springframework.boot spring-boot-starter-thymeleaforg.thymeleaf.extras thymeleaf-extras-springsecurity53.0.4.RELEASE
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.antMatchers("/hello").hasRole("USER")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest()
.authenticated()
.and()
.formLogin().loginPage("/login")
.usernameParameter("user")
.passwordParameter("pwd")
.defaultSuccessUrl("/hello").failureUrl("/login?logout").permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.logout().logoutSuccessUrl("/login?logout").permitAll();
.and()
.csrf().disable().headers().frameOptions().disable();
http.rememberMe().rememberMeParameter("remember");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("zs").password(new BCryptPasswordEncoder().encode("123456")).roles("USER");
}
}
3 权限控制
按照常规来说,不同的人进入首页后 应该显示不同权限所显示的内容 这个时候我们就需要thymeleaf与Security的整合
首先在页面中导入thymeleaf-Security的命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
登录
用户名:
权限:
注销
核心是这句判断,
IsAuthenticated 属性是一个布尔值,指示当前用户是否已通过身份验证(已登录)
明白了这个属性的作用 就等于理清了我们上面的思路
登录之后 有了登录角色的信息
接下来就是思考 vip不同等级的人应该有不同的展示页面
将对应的语句 放在对应权限才能访问的页面的第一个div标签中 进行判断 hasRole:拥有了角色 在这 我们可以理解为拥有的权限 大致意思就是 有vip1权限就显示vip1的内容 以此类推 设置完成后进行测试访问 没有登陆的情况下 我们没有任何权限 所以不显示任何内容记住我
上图就是设置与否的区别 这里的记住我的功能 相当于是将cookie保存了起来 即使我们页面关闭也不会丢失 cookie有效期为
注销
使用自己的登录页面完成注销功能 会有一个404的错误 这是Secruity自动开启了CSRF的脚本攻击校验 我们只需要关闭它即可
http.csrf().disable();
注意 security的配置文件中使用.defaultSuccessUrl(“/hello”)



