SpringBoot 整合Spring Security

Spring Security

目录

  • 1 Spring Security 简介
  • 2 搭建Spring Security 环境
  • 3 Spring Security 用户认证和授权
  • 4 SpringSecurity 注销,以及权限控制
  • 5 SpringSecurity 记住我以及首页定制
  • 6 完整配置

1 Spring Security 简介

  在 Web 开发中,安全一直是非常重要的一个方面。安全虽然属于应用的非功能性需求,但是应该在应用开发的初期就考虑进来。,从应用开发的第一天就应该把安全相关的因素考虑进来,并在整个应用的开发过程中。
对于权限 一般会细分为功能权限,访问权限,和菜单权限。代码会写的非常的繁琐,冗余。

  解决之前写权限代码繁琐,冗余的问题,一些主流框架就应运而生而Spring Scecurity就是其中的一种

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

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

  • Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权

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

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

对于上面提到的两种应用情景,Spring Security 框架都有很好的支持。在用户认证方面,

2 搭建Spring Security 环境

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

2、导入静态资源
  项目 gitee 地址 https://gitee.com/nutxi/springboot-security
在这里插入图片描述
3 controller跳转!

@Controller
public class RoutController {
    @RequestMapping({"/","/index"})
    public String index(){
        return "index";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }

    @RequestMapping("/level1/{id}")
    public String toLevel1(@PathVariable("id") Integer id){
        return "views/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String toLevel2(@PathVariable("id") Integer id){
        return "views/level2/"+id;
    }

    @RequestMapping("/level3/{id}")
    public String toLevel3(@PathVariable("id") Integer id){
        return "views/level3/"+id;
    }
}

4 测试实验环境

认识Spring Security

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

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略

  • AuthenticationManagerBuilder:自定义认证策略

  • @EnableWebSecurity:开启WebSecurity模式

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

“认证”(Authentication)

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

  • 身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
    “授权” (Authorization)

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

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

3 Spring Security 用户认证和授权

1 导入依赖

   <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- ... other dependency elements ... -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4   thymeleaf 整合 springsecurity5  -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

2 编写 Spring Security 配置类

参考官网:https://spring.io/projects/spring-security
参考文档 https://docs.spring.io/spring-security/site/docs/current/reference/html5/#jc Custom DLS位置


@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("/index").permitAll()
                     .antMatchers("/").permitAll()
                     .antMatchers("/level1/**").hasRole("vip1")
                     .antMatchers("/level2/**").hasRole("vip2")
                     .antMatchers("/level3/**").hasRole("vip3");
             //没有权限默认跳到登录页面
	// 开启自动配置的登录功能
	// /login 请求来到登录页
	// /login?error 重定向到这里表示登录失败
http.formLogin();
    }

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

8、查看刚才登录页的注释信息; 定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法

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

        //开启内存角色的认证
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("level1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("level2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
                .and()
                .withUser("level3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2");
    }


9、测试,如果没有编码 发现会报错!
在这里插入图片描述

为了确保安全,需要对密码进行编码

常用的密码编码器

  • 1 BCryptPasswordEncoder
       BCryptPasswordEncoder 实现使用广泛支持的 bcrypt 算法对密码进行散列
	BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(16);
		String result = encoder.encode("myPassword");
		assertTrue(encoder.matches("myPassword", result));
  • 2 Argon2PasswordEncoder
    Argon2PasswordEncoder 实现使用 Argon2算法对密码进行散列Argon2是密码散列竞赛的优胜者。为了在自定义硬件上击败密码破解,Argon2是一个故意降低速度的算法,需要大量的内存

  • 3 Pbkdf2PasswordEncoder

    Pbkdf2PasswordEncoder 实现使用 PBKDF2算法对密码进行散列。为了击败密码破解,PBKDF2是一个故意缓慢的算法。

  • 4 SCryptPasswordEncoder 实现使用 scrypt 算法对密码进行散列。为了在自定义硬件上击败密码破解,scrypt 是一个故意运行缓慢的算法

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

4 SpringSecurity 注销,以及权限控制

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

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
   //开启自动配置的注销的功能
      // /logout 注销请求 logoutrul 设置什么路径会跳转,   logoutSuccessUrl 跳转成功后的路径
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/index");
}

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

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

3 测试
发现跳转到首页OK

Thymeleaf 整合Spring -security

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

1 导入依赖 前面已经导入

2 导入命名空间

<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec=http://www.thymeleaf.org/extras/spring-security>

3 修改导航栏,增加认证判断


<div class="ui container">

    <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
        <div class="ui secondary menu">
            <a class="item"  th:href="@{/index}">首页</a>

            <!--登录注销-->
            <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">
                        Logged user: <span sec:authentication="name"></span>
                        Roles: <span sec:authentication="principal.authorities"></span>
                    </a>
                </div>
                <div sec:authorize="isAuthenticated()">
                    <a class="item" th:href="@{/logout}">
                        <i class="sign-out icon"></i> 注销
                    </a>
                </div>



                <!--已登录
                <a th:href="@{/usr/toUserCenter}">
                    <i class="address card icon"></i> admin
                </a>
                -->
            </div>
        </div>
    </div>


  • sec:authorize=“isAuthenticated()”:是否认证登录
  • sec:authentication=“name” 获取认证的用户名
  • sec:authentication=“principal.authorities” 获取认证的角色

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

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

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

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


<!-- sec:authorize="hasRole('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>

<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>

<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>

sec:authorize=“hasRole(‘vip1’)” 判断用户是否有某个角色

11、测试一下!

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

5 SpringSecurity 记住我以及首页定制

我们只要登录之后,关闭浏览器,再登录,就会让我们重新登录,但是很多网站的情况,就是有一个记住密码的功能
1 开启记住我功能

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

2 实现原理 通过cookie
在这里插入图片描述

3 定制登录页

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

    http.formLogin().loginPage("/toLogin").usernameParameter("nickname").passwordParameter("pwd")

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

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

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


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

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

       <div class="field">
                                <div class="ui checkbox">
                                    <input type="checkbox" tabindex="0" name="remember-me">
                                    <label>REMEMBER ME</label>
                                </div>
                            </div>

7、测试,OK

6 完整配置

package com.kuang.config;


import org.springframework.context.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig  extends WebSecurityConfigurerAdapter  {
        //用户授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
            //首页所有的人都能访问
             http.authorizeRequests()
                     .antMatchers("/index").permitAll()
                     .antMatchers("/").permitAll()
                     .antMatchers("/level1/**").hasRole("vip1")
                     .antMatchers("/level2/**").hasRole("vip2")
                     .antMatchers("/level3/**").hasRole("vip3");
             //没有权限默认跳到登录页面
        http.formLogin().loginPage("/toLogin").usernameParameter("nickname").passwordParameter("pwd").loginProcessingUrl("/index");
        http.csrf().disable();
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/index");
        http.rememberMe().rememberMeParameter("remember-me");

    }
         //创建用户角色,权限认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //开启内存角色的认证
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("level1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("level2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
                .and()
                .withUser("level3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2");
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值