在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的初期就考虑进来。如果在应用开发的后期才考虑安全的问题,就可能陷入一个两难的境地:一方面,应用存在严重的安全漏洞,无法满足用户的要求,并可能造成用户的隐私数据被攻击者窃取;另一方面,应用的基本架构已经确定,要修复安全漏洞,可能需要对系统的架构做出比较重大的调整,因而需要更多的开发时间,影响应用的发布进程。因此,从应用开发的第一天就应该把安全相关的因素考虑进来,并在整个应用的开发过程中。
Java Web项目的权限管理框架,目前有两个比较成熟且使用较多的框架,Shiro 和 Spring Security ,Shiro 比 Spring Security更加轻量级,但是需要手动配置的东西较多,Spring Security 和 Spring 集成更好,甚至直接适配了Spring Boot。
这里我准备的是一个首页一个登录页面,以及三个vip等级对应的3个页面、
静态资源放到static目录下、views放到templates下
下载链接:https://files.cnblogs.com/files/zhangzhixi/SpringBoot-SpringSecurity%E7%B4%A0%E6%9D%90.rar
Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
加入依赖后,会自动获取Spring Security 5.1.5版本的Jar包:
然后,,一个基本的Spring Security已经有了,然后打开浏览器,访问http://localhost:8080,神奇的出来了一个登录页面,但是并没有创建任何的html文件、
登录security提供的默认login页面:
username:user
password:是在控制台打印的一串UUID
然后就可以登录到我们的首页了。
编写了配置类,security的默认配置就不会生效了(不会直接跳转到login页面,而是直接访问主页)、依照我们自己的配置来:
@EnableWebSecurity // 开启WebSecurity模式
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();
此时如果没有权限就会跳转至登陆页
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//数据正常应该从数据库中取,现在从内存中取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
// 设置用户名密码以及能够访问的权限设置
.withUser("admin").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
}
就是说我们能够访问首页,如果想进入到别的页面就需要登录:
什么用户对应什么权限,比如我使用了admin用户登录成功后,可以访问vip1和vip2的页面,但是访问不了vip3的页面!
这里设置密码加密auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) 否则会报There is no PasswordEncoder mapped for the id"null"错误, 创建的每个用户也必须添加密码加密**.password(new BCryptPasswordEncoder().encode("123"))**
原文:https://www.cnblogs.com/zhangzhixi/p/14340219.html