SpringBoot与安全
比较常用的安全框架:shiro跟Spring Security
Spring Security使用
1、引入Spring Security
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、编写Spring Security的配置类
@EnableWebSecurity // 已经带了@Configuration注解了,不用再使用@Configuration注解了
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
}
登录 & 角色 & 登出
@EnableWebSecurity // 已经带了@Configuration注解了,不用再使用@Configuration注解了
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
// 定义授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll() // 允许所有人访问根路径
.antMatchers("/level1/**").hasRole("VIP1") // 即要想访问/level1下的所有请求都必须拥有VIP1的角色
.antMatchers("/level2/**").hasRole("VIP2"); // 要想访问/level2下的所有请求都必须拥有VIP2的角色
// 开启自动配置的登录功能,默认去/login页面。效果:如果没有权限会来到登录页面
http.formLogin();
// 开启自动配置的注销功能,访问/logout表示用户注销,必须发送post请求
http.logout()
.logoutSuccessUrl("/"); // 退出成功后跳转的地址
}
// 定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication() // 将用户名跟密码角色等放到内存中
.withUser("zhangsan").password("123456").roles("VIP1", "VIP2") // 定义用户 密码 分配角色
.and()
.withUser("lisi").password("123").roles("VIP1"); // 再添加一个用户
}
}
权限控制
1、引入thymeleaf跟spring security的依赖
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
2、在html页面引入security的名称空间
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
3、判断权限相关
<!-- 判断是否登录 -->
<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')">
如果有VIP1的角色怎样。。。
</div>
记住我 & 定制登录页
记住我
// 定义授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
// 开启记住我功能
http.rememberMe()
.rememberMeParameter("remember"); // 表单提交的name参数
}
定制登录页
// 定义授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.usernameParameter("user") // 自定制页面中提交的name属性
.passwordParameter("pwd")
.loginProcessingUrl("/login") // 处理认证的url,如果不配置就默认去当前url的post请求认证
.loginPage("/userlogin"); // 修改登录的页面
// 开启记住我功能
http.rememberMe()
.rememberMeParameter("remember"); // 表单提交的name参数
}

浙公网安备 33010602011771号