Spring Security学习

前面所学能简单实现安全的有过滤器和拦截器。需要掌握过滤器和拦截器的原理和使用(基础)

1 安全简介

Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。

  • 用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码,系统通过校验用户名和密码来完成认证过程。
  • 用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

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

SpringSecurity功能:

  • 认证
  • 授权(给予用户权限)
    • 功能权限
    • 访问权限
    • 菜单权限

AOP思想,横切代码

2 Spring Security介绍

Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

  1. “认证”(Authentication)

    • 身份验证是关于验证您的凭据,如用户名 / 用户ID和密码,以验证您的身份。

    • 身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

  2. “授权” (Authorization)

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

实例

2.1 认证和授权

  1. 引入SpringSecurity依赖

    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  2. 编写 Spring Security 配置类

    • 参考官网:https://spring.io/projects/spring-security
  3. 编写基础配置类

    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @EnableWebSecurity // 开启WebSecurity模式
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
       @Override
       protected void configure(HttpSecurity http) throws Exception {
           
      }
    }
    
  4. 定制请求的授权规则

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //链式编程
        http.authorizeRequests().antMatchers("/").permitAll() //首页所有人可以访问
       .antMatchers("/level1/**").hasRole("vip1"); //表示vip1角色可以访问level1下的页面
    }
    
  5. 开启自动配置的登录功能,在configure()方法中加入以下配置

    /* 开启自动配置的登录功能 
    	/login 请求来到登录页
     	/login?error 重定向到这里表示登录失败
    */
    http.formLogin();
    
  6. 定制认证规则

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     //在内存中定义,也可以在jdbc中去拿....
        auth.inMemoryAuthentication()
            .withUser("xxx").password("123456").roles("vip2","vip3")
            .and()
            .withUser("root").password("123456").roles("vip1","vip2","vip3");
    }
    
  7. 密码需要实现加密功能

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以在jdbc中去拿....
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
        //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
        //spring security 官方推荐的是使用bcrypt加密方式。
    
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("xxxx").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
            .and()
            .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }
    

2.2 权限控制和注销

  • 开启自动配置的注销的功能

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       // /logout 注销请求
       http.logout();
    }
    
  • 功能:相应的用户能看到对应的模块。需要结合thymeleaf中的一些功能

    • sec:authorize=“isAuthenticated()”:是否认证登录!来显示不同的页面

    • 导入maven依赖

      <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
      <dependency>
         <groupId>org.thymeleaf.extras</groupId>
         <artifactId>thymeleaf-extras-springsecurity5</artifactId>
         <version>3.0.4.RELEASE</version>
      </dependency>
      
    • 在前端页面中导入命名空间

      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
      
    • 修改导航栏,增加认证判断

      <!--登录注销-->
      <div class="right menu">
      
         <!--如果未登录-->
         <div sec:authorize="!isAuthenticated()">
             <a class="item" th:href="@{/login}">
                 <i class="address card icon"></i> 登录
             </a>
         </div>
      
         <!--如果已登录-->
         <div sec:authorize="isAuthenticated()">
             <a class="item">
                 <i class="address card icon"></i>
                用户名:<span sec:authentication="principal.username"></span>
                角色:<span sec:authentication="principal.authorities"></span>
             </a>
         </div>
      
         <div sec:authorize="isAuthenticated()">
             <a class="item" th:href="@{/logout}">
                 <i class="address card icon"></i> 注销
             </a>
         </div>
      </div>
      
  • 如果注销404了,就是因为它默认防止csrf跨站请求伪造(网站攻击),因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在配置中增加 http.csrf().disable();

    http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求http.logout().logoutSuccessUrl("/");
    
  • 注册成功跳转页面

    // .logoutSuccessUrl("/"); 注销成功来到首页
    http.logout().logoutSuccessUrl("/");
    

2.3 记住我功能实现

现在的情况,我们只要登录之后,关闭浏览器,再登录,就会让我们重新登录,但是很多网站的情况,就是有一个记住密码的功能,这个该如何实现呢?很简单 :

1、开启记住我功能

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.logout();
    //记住我
    http.rememberMe();
}

2、我们再次启动项目测试一下,发现登录页多了一个记住我功能,我们登录之后关闭 浏览器,然后重新打开浏览器访问,发现用户依旧存在!

  • 原理:当点击注销的时候,SpringBoot自动删除了这个cookie

登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,则会删除这个cookie。

2.4定制登录页面

现在这个登录页面都是spring security 默认的,怎么样可以使用我们自己写的Login界面呢?

1、在刚才的登录页配置后面指定 loginpage

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin().loginPage("/toLogin");
    //http.logout();
    //记住我
    http.rememberMe();
}

2、然后前端也需要指向我们自己定义的 login请求

<a class="item" th:href="@{/toLogin}">   <i class="address card icon"></i> 登录</a>

3、定制记住我的参数!

http.rememberMe().rememberMeParameter("remember");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值