• SpringSecurity安全管理


    SpringSecurity安全管理

    一、安全简介

    在 Web 开发中,安全一直是非常重要的一个方面,因此从应用开发的第一天就应该把安全相关的因素考虑进来,并在整个应用的开发过程中。

    主要安全框架:Shiro,Spring Security

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

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

    这是一个权限框架,权限 一般会细分为功能权限,访问权限,和菜单权限,代码会写的非常的繁琐,冗余。

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

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

    二、认识SpringSecurity

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

    记住几个类:

    • WebSecurityConfigurerAdapter:自定义Security策略
    • AuthenticationManagerBuilder:自定义认证策略
    • @EnableWebSecurity:开启WebSecurity模式
      Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

    “认证”(Authentication)

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

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

    “授权” (Authorization)

    授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

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

    三、认证和授权

    1.引入 Spring Security 模块

    <dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-securityartifactId>
    dependency>

    2.编写 Spring Security 配置类

    基础配制

    参考帮助文档:

    https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/pdf/spring-security-reference.pdf

    package com.dyt.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;
    @EnableWebSecurity // 开启WebSecurity模式
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    }
    }

    3.定制请求的授权规则

    //授权
    // 链式编程
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //首页所有人可以访问,功能页只有对应有权限的人才能访问
    //请求授权的规则
    http.authorizeRequests()
    .antMatchers("/").permitAll()
    .antMatchers("/level1/**").hasRole("vip1")
    .antMatchers("/level2/**").hasRole("vip2")
    .antMatchers("/level3/**").hasRole("vip3");
    //没有权限默认会到登录页面,需要开启登录页面
    // /login 请求来到登录页
    // /login?error 重定向到这里表示登录失败
    http.formLogin();
    }

    4.测试一下:发现,没有权限的时候,会跳转到登录的页面!

    image

    5.认证规则

    重写configure(AuthenticationManagerBuilder auth)方法

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

    测试,发现,登录成功,并且每个角色只能访问自己认证下的规则!搞定

    四.权限控制和注销

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

    //定制请求的授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    //....
    //开启自动配置的注销的功能
    // /logout 注销请求
    http.logout();
    }

    2、我们在前端,增加一个注销的按钮,index.html 导航栏中

    <a class="item" th:href="@{/logout}">
    <i class="address card icon">i> 注销
    a>

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

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

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

    5、测试,注销完毕后,发现跳转到首页OK

    6、我们现在又来一个需求

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

    我们需要结合thymeleaf中的一些功能

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

    Maven依赖:

    <dependency>
    <groupId>org.thymeleaf.extrasgroupId>
    <artifactId>thymeleaf-extras-springsecurity5artifactId>
    <version>3.0.4.RELEASEversion>
    dependency>

    7、修改我们的 前端页面

    导入命名空间

    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>

    8、重启测试,我们可以登录试试看,登录成功后确实,显示了我们想要的页面;

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

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

    10、我们继续将下面的角色功能块认证完成!

    <div class="column" sec:authorize="hasRole('vip1')">
    <div class="ui raised segment">
    <div class="ui">
    <div class="content">
    <h5 class="content">Level 1h5>
    <hr>
    <div><a th:href="@{/level1/1}"><i class="bullhorn icon">i> Level-1-1a>div>
    <div><a th:href="@{/level1/2}"><i class="bullhorn icon">i> Level-1-2a>div>
    <div><a th:href="@{/level1/3}"><i class="bullhorn icon">i> Level-1-3a>div>
    div>
    div>
    div>
    div>
    <div class="column" sec:authorize="hasRole('vip2')">
    <div class="ui raised segment">
    <div class="ui">
    <div class="content">
    <h5 class="content">Level 2h5>
    <hr>
    <div><a th:href="@{/level2/1}"><i class="bullhorn icon">i> Level-2-1a>div>
    <div><a th:href="@{/level2/2}"><i class="bullhorn icon">i> Level-2-2a>div>
    <div><a th:href="@{/level2/3}"><i class="bullhorn icon">i> Level-2-3a>div>
    div>
    div>
    div>
    div>
    <div class="column" sec:authorize="hasRole('vip3')">
    <div class="ui raised segment">
    <div class="ui">
    <div class="content">
    <h5 class="content">Level 3h5>
    <hr>
    <div><a th:href="@{/level3/1}"><i class="bullhorn icon">i> Level-3-1a>div>
    <div><a th:href="@{/level3/2}"><i class="bullhorn icon">i> Level-3-2a>div>
    <div><a th:href="@{/level3/3}"><i class="bullhorn icon">i> Level-3-3a>div>
    div>
    div>
    div>
    div>

    11、测试一下!

    12、权限控制和注销搞定!

    五.记住我

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

    1、开启记住我功能

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

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

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

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

    六.定制登录页

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

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

    http.formLogin().loginPage("/toLogin");

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

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

    3、我们登录,需要将这些信息发送到哪里,我们也需要配置,login.html 配置提交请求及方式,方式必须为post:

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

    <form th:action="@{/login}" method="post">
    <div class="field">
    <label>Usernamelabel>
    <div class="ui left icon input">
    <input type="text" placeholder="Username" name="username">
    <i class="user icon">i>
    div>
    div>
    <div class="field">
    <label>Passwordlabel>
    <div class="ui left icon input">
    <input type="password" name="password">
    <i class="lock icon">i>
    div>
    div>
    <input type="submit" class="ui blue submit button"/>
    form>

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

    http.formLogin()
    .usernameParameter("username")
    .passwordParameter("password")
    .loginPage("/toLogin")
    .loginProcessingUrl("/login"); // 登陆表单提交请求

    5、在登录页增加记住我的多选框

    <input type="checkbox" name="remember"> 记住我

    6、后端验证处理!

    //定制记住我的参数!
    http.rememberMe().rememberMeParameter("remember");

    7、测试,OK

    完整配制代码

    package com.dyt.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;
    //AOP 横切 拦截器
    @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()
    .usernameParameter("username")
    .passwordParameter("password")
    .loginPage("/toLogin")
    .loginProcessingUrl("/login"); // 登陆表单提交请求
    http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
    //记住我
    http.rememberMe().rememberMeParameter("remember");
    //开启自动配置的注销的功能
    // /logout 注销请求
    // .logoutSuccessUrl("/"); 注销成功来到首页
    http.logout().logoutSuccessUrl("/");
    }
    //认证
    //在内存中定义,也可以在jdbc中去拿....
    //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
    //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
    //spring security 官方推荐的是使用bcrypt加密方式。
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
    .withUser("gdh").password(new BCryptPasswordEncoder().encode("123")).roles("vip2","vip3")
    .and()
    .withUser("root").password(new BCryptPasswordEncoder().encode("456")).roles("vip1","vip2","vip3")
    .and()
    .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("vip1");
    }
    }

本文作者:二价亚铁

本文链接:https://www.cnblogs.com/xw-01/p/18288051

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

  • 相关阅读:
    数模5—蒙特卡洛算法、灰色预测
    零基础入门microbit教程
    2.CF242E XOR on Segment 线段树维护区间反转
    VUE+Element首次打开Dialog加载子组件数据未渲染(不显示)
    【MQTT】Esp32数据上传采集:最新mqtt插件(支持掉线、真机调试错误等问题)
    [游戏开发][Unity] ScriptableObject数据创建与各种加载方式
    高效的软件测试策略指南
    MyBatis-Plus(二)
    Spring Boot 注解
    有想去做的事,早早去做
  • 原文地址:https://www.cnblogs.com/xw-01/p/18288051