• SpringSecurity配置


    SpringSecurity

    功能

    spring security 的核心功能主要包括:

    • 认证 (你是谁)

    • 授权 (你能干什么)

    • 攻击防护 (防止伪造身份)

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

    • WebSecurityConfigurerAdapter: 自定义Security策略

    • AuthenticationManagerBuilder: 自定义认证策略

    • @EnableWebSecurity: 开启WebSecurity模式 @EnableXXXX 开启某个功能

    认证&授权

    1. 要想使用springsecurity,要引入依赖

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    1. 配置类

    @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");


           //没有权限,默认跳到登录页面
           //login
           //定制登陆页面,登陆成功之后 自动跳转到index.html(首页)页面,
           // .usernameParameter("") 设置username参数 默认是username,和前端的name属性要一致
           http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");

           //注销功能
           //防止跨站攻击
           http.csrf().disable();
           http.logout().logoutSuccessUrl("/");

           //开启记住我功能 cookies+session实现 , 自定义记住我功能
           http.rememberMe().rememberMeParameter("remember");
      }

       //认证
       @Override
       protected void configure(AuthenticationManagerBuilder auth) throws Exception {

           auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                  .withUser("Gao").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                  .and()
                  .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip3");
      }
    }
    1. 配置授权的规则

       @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
             //定制登陆页面,登陆成功之后 自动跳转到index.html(首页)页面,
             // .usernameParameter("") 设置username参数 默认是username,和前端的name属性要一致
             http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");

             //注销功能
             //防止跨站攻击
             http.csrf().disable();
             http.logout().logoutSuccessUrl("/");

             //开启记住我功能 cookies+session实现 , 自定义记住我功能
             http.rememberMe().rememberMeParameter("remember");
        }
      1. 定义认证规则

      //定义认证规则
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       
        //在内存中定义,也可以在jdbc中去拿....
        auth.inMemoryAuthentication()
              .withUser("kuangshen").password("123456").roles("vip2","vip3")
              .and()
              .withUser("root").password("123456").roles("vip1","vip2","vip3")
              .and()
              .withUser("guest").password("123456").roles("vip1","vip2");
      }
      1. 仅仅这样会报错:There is no PasswordEncoder mapped for the id “null”,原因,我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码。

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

      权限控制和注销

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

       //注销功能
         //防止跨站攻击
         http.csrf().disable();
         http.logout().logoutSuccessUrl("/");// .logoutSuccessUrl("/"); 注销成功之后进入的页面
      1. 我们现在又来一个需求:

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

        我们需要结合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="@{/toLogin}">
                               <i class="address card icon"></i> 登录
                           </a>
                       </div>

                       <!--已经登录则显示用户名和注销按钮-->
                       <div sec:authorize="isAuthenticated()">
                           <a class="item">
                              用户名:<span sec:authentication="name"></span>
                           </a>
                       </div>
                       <div sec:authorize="isAuthenticated()">
                           <a class="item" th:href="@{/logout}">
                               <i class="sign-out card icon"></i> 注销
                           </a>
                       </div>
        1. 如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在 配置中增加 http.csrf().disable();

        2. 角色认证模块

          <div>
                 <br>
                 <div class="ui three column stackable grid">
                     <!-- 如果有VIP1角色,就显示下面内容-->
                     <div class="column" sec:authorize="hasRole('vip1')">
                         <div class="ui raised segment">
                             <div class="ui">
                                 <div class="content">
                                     <h5 class="content">Level 1</h5>
                                     <hr>
                                     <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
                                     <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
                                     <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
                                 </div>
                             </div>
                         </div>
                     </div>
          <!-- 如果有VIP2角色,就显示下面内容-->
                     <div class="column" sec:authorize="hasRole('vip2')">
                         <div class="ui raised segment">
                             <div class="ui">
                                 <div class="content">
                                     <h5 class="content">Level 2</h5>
                                     <hr>
                                     <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
                                     <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
                                     <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
                                 </div>
                             </div>
                         </div>
                     </div>
          <!-- 如果有VIP3角色,就显示下面内容-->
                     <div class="column" sec:authorize="hasRole('vip3')">
                         <div class="ui raised segment">
                             <div class="ui">
                                 <div class="content">
                                     <h5 class="content">Level 3</h5>
                                     <hr>
                                     <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
                                     <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
                                     <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
                                 </div>
                             </div>
                         </div>
           
                     </div>

                 </div>
             </div>

    记住我

    1. 功能实现

      //开启记住我功能  cookies+session实现  , 自定义记住我功能
             http.rememberMe().rememberMeParameter("remember");
    2. 原理:

      登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,则会删除这个cookie,具体的原理我们在JavaWeb阶段都讲过了,这里就不在多说了!

    定制登录页

    现在这个登录页面都是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>Username</label>
          <div class="ui left icon input">
              <input type="text" placeholder="Username" name="username">
              <i class="user icon"></i>
          </div>
      </div>
      <div class="field">
          <label>Password</label>
          <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

  • 相关阅读:
    Myeclipse如何使用自带git工具向远程仓库提交代码
    myEclipse配置java版本(环境、项目、编译)
    新搭建项目时需要修改的内容
    干锅土豆
    SpringMVC MongoDB之“基本文档查询(Query、BasicQuery)”
    史上最全web.xml配置文件元素详解
    Web.xml配置详解之context-param
    史上最全的maven的pom.xml文件详解
    MongoDB 进阶模式设计
    备忘整理
  • 原文地址:https://www.cnblogs.com/g414056667/p/14714743.html
Copyright © 2020-2023  润新知