SpringBoot集成Security

安全介绍

在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的初期就考虑进来。如果在应用开发的后期才考虑安全的问题,就可能陷入一个两难的境地:一方面,应用存在严重的安全漏洞,无法满足用户的要求,并可能造成用户的隐私数据被攻击者窃取;另一方面,应用的基本架构已经确定,要修复安全漏洞,可能需要对系统的架构做出比较重大的调整,因而需要更多的开发时间,影响应用的发布进程。因此,从应用开发的第一天就应该把安全相关的因素考虑进来,并在整个应用的开发过程中。

SpringSecurity官网介绍:
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements

SpringSecurity是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。

Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求。

之前做项目是没有使用框架是怎么控制权限的?对于权限 一般会细分为功能权限,访问权限,和菜单权限。代码会写的非常的繁琐,冗余,怎么解决之前写权限代码繁琐,冗余的问题,一些主流框架就应运而生而Spring Scecurity就是其中的一种。

Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。

准备工作

  1. 导入web、thymeleaf、SpringSecurity依赖
<!--        thymeleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--        web依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

<!--      SpringSecurity依赖  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--        springboot测试依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
  1. 导入相应的静态页面测试
    在这里插入图片描述

  2. 先不添加SpringSecurity依赖时,页面全部可以正常访问,当我们添加SpringSecurity依赖时,springboot自动帮我们启动SpringSecurity默认用户认证和用户授权,当我们启动项目跳转任意请求时都会指向/login请求页面
    在这里插入图片描述

  3. 此时控制台给我们生成了一串UUID的密码,此时并不知道用户名是什么,我们去SpringSecurity配置文件中查找一下,springboot的配置文件都是XXX.properties,我们搜索一下SecurityProperties,发现有默认的username,和随机生成UUID作为密码,即输入正确后才能进入首页
    在这里插入图片描述

在这里插入图片描述

使用SpringSecurity进行用户认真和授权

SpringSecurity是针对Spring项目的安全框架,也是SpringBoot底层安全模块默认的技术选型,他可以实现强大的Web安全控制

  1. SpringSecurity有几个类和注解需要使用到

WebSecurityConfigurerAdapter:自定义Security策略

AuthenticationManagerBuilder:自定义认证策略

@EnableWebSecurity:开启WebSecurity模式

认证(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用

授权(Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。
这个概念是通用的,而不是只在Spring Security 中存在。

  1. 配置自定义认证和授权(访问控制)类

在这里插入图片描述

//开启WebSecurity模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   

    
}
  1. 定制请求的授权规则
//开启WebSecurity模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   

    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        // 定制请求的授权规则, 首页(/、index)所有人可以访问
        http.authorizeRequests().antMatchers("/","index").permitAll()
        //其他请求url分别设置角色权限才能进行访问
        .antMatchers("/level1/**").hasRole("vip1")
        .antMatchers("/level2/**").hasRole("vip2")
        .antMatchers("/level3/**").hasRole("vip3");
    }
}
  1. 启动项目访问,发现除了index.html首页可以访问,其他页面都没有权限访问,因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以访问

  2. 在configure()方法中加入配置,开启自动配置的登录功能

		// 开启自动配置的登录功能
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        http.formLogin();
  1. 启动项目测试后发现,当没有权限时候,会跳转到登录的页面

在这里插入图片描述

  1. 我们在HttpSecurity类中可以看到以下注释信息,因此我们可以定义认证规则,重新configure(AuthenticationManagerBuilder auth)方法
 * @Configuration
 * @EnableWebSecurity
 * public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {
   
 *
 * 	@Override
 * 	protected void configure(HttpSecurity http) throws Exception {
   
 * 		http.authorizeRequests().antMatchers(/**).hasRole(USER).and().formLogin();
 * 	}
 *
 * 	@Override
 * 	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
 * 		auth.inMemoryAuthentication().withUser(user).password(password).roles(USER);
 * 	}
  //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        //在内存中定义,也可以在jdbc中去拿对应username、password、roles对应的值
        auth.inMemoryAuthentication().withUser("chenhui").password("123456").roles("vip2","vip3").
        and().withUser("user").password("123456").roles("vip1").
        and().withUser("root").password("123456").roles("vip1","vip2","vip3");
    }

当启动项目进行测试时,当使用我们设置好的账号密码进行登录认证时,发现一个错误
在这里插入图片描述

原因是:要将前端传过来的密码进行某种方式加密,否则就无法登录

//表示是Spring一个配置文件(组件)
@Configuration
//开启WebSecurity模式
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   


    /**
        The default configuration is:
     * http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
     * Any endpoint that requires defense against common vulnerabilities can be specified
     * here, including public ones. See {@link HttpSecurity#authorizeRequests} and the
     * `permitAll()` authorization rule for more details on public endpoints.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
   
        // 定制请求的授权规则, 首页(/、index)所有人可以访问
        http.authorizeRequests().antMatchers("/","index").permitAll()
                //其他请求分别设置角色权限进行访问
                .antMatchers("/level1/**").hasRole("vip1"
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值