SpringSecurity

SpringSecurity是一个强大的Java安全框架,用于身份验证和访问控制。它提供用户认证和授权功能,支持多种认证方式和细粒度的权限管理。通过配置,可以实现如首页公开,其他页面需特定角色访问等功能。此外,还支持记住密码、自定义登录页面以及防止CSRF攻击等特性。
摘要由CSDN通过智能技术生成

1、SpringSecurity

官网地址:https://spring.io/projects/spring-security

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

市面上存在比较有名的:Shiro,Spring Security !

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于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.1、简介

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

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

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

  • “认证”(Authentication)

  • “授权” (Authorization)

    这个概念是通用的,而不是只在Spring Security 中存在

1.2、使用SpringSecurity

  1. 新建一个初始的springboot项目web模块,thymeleaf模块

  2. 导入Spring Security 模块

     <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
  3. 导入静态资源

    index.html
    |views
    |level1
    1.html
    2.html
    3.html
    |level2
    1.html
    2.html
    3.html
    |level3
    1.html
    2.html
    3.html
    Login.html
    
  4. 使用controller实现页面的跳转

    package com.gjy.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class RouterController {
    
            @RequestMapping({"/","/index"})
            public String index(){
                return "index";
            }
    
            @RequestMapping("/toLogin")
            public String toLogin(){
                return "views/login";
            }
    
            @RequestMapping("/level1/{id}")
            public String level1(@PathVariable("id") int id){
                return "views/level1/"+id;
            }
    
            @RequestMapping("/level2/{id}")
            public String level2(@PathVariable("id") int id){
                return "views/level2/"+id;
            }
    
            @RequestMapping("/level3/{id}")
            public String level3(@PathVariable("id") int id){
                return "views/level3/"+id;
            }
    
    
    }
    
  5. 编写基础配置类

    package com.gjy.config;
    
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    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;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        //授权
        @Override
        protected void configure(HttpSecurity http) throws Exception {
           
        }
    
    }
    
    
  6. 定制请求的授权规则

    package com.gjy.config;
    
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    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;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    @EnableWebSecurity
    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");
        }
    
    }
    
    
  7. 测试:发现除了首页都进不去了!因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以

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

    http.formLogin();
    
  9. 测试:发现,没有权限的时候,会跳转到登录的页面

  10. 查看刚才登录页的注释信息,我们可以定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法

  11. 测试,我们可以使用这些账号登录进行测试!发现会报错!There is no PasswordEncoder mapped for the id “null”

  12. 原因,我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码

    package com.gjy.config;
    
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    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;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    @EnableWebSecurity
    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();
        }
    
        //认证
        //PasswordEncoder  密码加密
        //这些数据正常应该从数据库中获取
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("gjy").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                    .and()
                    .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3").and()
                    .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
        }
    }
    
  13. 测试,发现,登录成功,并且每个角色只能访问自己认证下的规则

1.3、权限控制和注销

  1. 开启自动配置的注销的功能

    //注销
    http.logout();
    
  2. 我们在前端,增加一个注销的按钮,index.html 导航栏中

  3. 我们可以去测试一下,登录成功后点击注销,发现注销完毕会跳转到登录页面

  4. 但是,我们想让他注销成功后,依旧可以跳转到首页,该怎么处理呢?

    //注销
    http.logout().logoutSuccessUrl("/");
    
  5. 测试,注销完毕后,发现跳转到首页OK

  6. 我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!还有就是,比如gjy这个用户,它只有 vip2,vip3功能,那么登录则只显示这两个功能,而vip1的功能菜单不显示!这个就是真实的网站情况了!该如何做呢?

  7. 我们需要结合thymeleaf中的一些功能 sec:authorize=“isAuthenticated()”:是否认证登录!来显示不同的页面

    Maven依赖:

     <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>3.0.4.RELEASE</version>
    </dependency>
    
  8. 修改我们的前端页面 导入命名空间

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

    <!DOCTYPE html>
    <html lang="en" xmlns:th="https://www.thymeleaf.org/"
          xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <div style="margin-top: 50px;">
        <a href="/index" style="font-size: 25px;">首页</a>
    </div>
    <!--如果登录 显示注销和用户名-->
    <div sec:authorize="isAuthenticated()">
        <a class="item" th:href="@{/logout}">
            <i class="sign out 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="@{/toLogin}">
            <i class="address card icon"></i> 登录
        </a>
    </div>
    <div style="margin: 50px;" sec:authorize="hasRole('vip1')">
        <a href="/level1/1">level1-1</a>
        <a href="/level1/2">level1-2</a>
        <a href="/level1/3">level1-3</a>
    </div>
    
    <div style="margin: 50px;" sec:authorize="hasRole('vip2')">
        <a href="/level2/1">level2-1</a>
        <a href="/level2/2">level2-2</a>
        <a href="/level2/3">level2-3</a>
    </div>
    <div style="margin: 50px;" sec:authorize="hasRole('vip3')">
        <a href="/level3/1">level3-1</a>
        <a href="/level3/2">level3-2</a>
        <a href="/level3/3">level3-3</a>
    </div>
    </body>
    </html>
    
  10. 重启测试,我们可以登录试试看,登录成功后确实,显示了我们想要的页面

  11. 如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在 配置中增加 http.csrf().disable();

     http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
    
  12. 我们继续将下面的角色功能块认证完成

  13. 测试

1.4、记住密码

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

  1. 开启记住我功能

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

    思考:如何实现的呢?其实非常简单

    我们可以查看浏览器的cookie
    在这里插入图片描述

  3. 我们点击注销的时候,可以发现,spring security 帮我们自动删除了这个 cookie

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

1.5、定制登录页

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

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

     //定制登录页    
    http.formLogin().loginPage("/toLogin");
    
  2. 然后前端也需要指向我们自己定义的 login请求

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">
        <title>Signin Template for Bootstrap</title>
        <!-- Bootstrap core CSS -->
        <link th:href="@{/css/bootstrap.min.css}" th:rel="stylesheet">
        <!-- Custom styles for this template -->
        <link th:href="@{/css/signin.css}" th:rel="stylesheet">
    </head>
    
    <body class="text-center">
    <form class="form-signin" th:action="@{/login}" method="post">
        <img class="mb-4" th:src="@{/img/bootstrap-solid.svg}" alt="" width="72" height="72">
        <h1 class="h3 mb-3 font-weight-normal">请登录</h1>
        
        <label class="sr-only">用户名</label>
        <input type="text" name="username" class="form-control"  required="" autofocus="" placeholder="用户名">
        <label class="sr-only">密码</label>
        <input type="password" name="password" class="form-control" required="" placeholder="密码">
        <div class="checkbox mb-3">
            <label>
                <input type="checkbox" name="remember" > 记住我
            </label>
        </div>
        <button class="btn btn-lg btn-primary btn-block" type="submit" >登录</button>
        <p class="mt-5 mb-3 text-muted">© 2017-2018</p>
    </form>
    
    </body>
    
    </html>
    
  3. 我们登录,需要将这些信息发送到哪里,我们也需要配置,login.html 配置提交请求及方式,方式必须为post:

    在 loginPage()源码中的注释上有写明:

  4. 这个请求提交上来,我们还需要验证处理,怎么做呢?我们可以查看formLogin()方法的源码!我们配置接收登录的用户名和密码的参数!

    http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");
    
  5. 在登录页增加记住我的多选框

  6. 后端验证处理

  7. 测试

完整配置代码

package com.gjy.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
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().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        //注销
        http.logout().logoutSuccessUrl("/");
        http.rememberMe().rememberMeParameter("remember");//开启记住我功能  实现记住密码
    }

    //认证
    //PasswordEncoder  密码加密
    //这些数据正常应该从数据库中获取
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("gjy").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3").and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值