1.SpringSecurity简介

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

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

2.SpringSecurity的使用

2.1新建一个SpringBoot项目

在Idea中新建一个SpringBoot项目,直接可以使用Spring Initializr方式创建一个SpringBoot项目,在选着依赖的时候可以直接勾选Security依赖

springboot身份证OCR springbootsecurity 认证_springboot身份证OCR


也可以直接创建,后面通过pom.xml来导入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
  </dependency>

这里我使用Thymeleaf模板引擎来操作前端页面,所以还要导入thymeleaf依赖和thymeleaf-sercurity依赖

<!-- thymeleaf依赖-->
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 <!-- thymeleaf中使用Security依赖,不导入会报一系列问题-->
 <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
 </dependency>

基本操作做完之后,开始正式用起来.

2.2实际操作

首先创建一个config包,这个包下创建一个关于Security的配置文件SecurityConfig配置类

package com.tangyu.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");
        //这个代码意思是前端表单中用户名和密码都变动了,不是username和password,则采用这个方法改成,变动的,这样sercurity才能获取到
        //loginProcessingUrl方法,/登陆表单提交请求
        http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        //防止网址工具:get post
        http.csrf().disable();//关闭CSRF功能,登录失败的原因
        //注销功能开启,登录之后,可以点击注销,让登录关闭
        http.logout().logoutSuccessUrl("/");

        //rememberMe方法开启记住我功能 coockie 默认保存两周,rememberMeParameter自定义接受前端参数,一般默认remember-me
        http.rememberMe().rememberMeParameter("remember");

    }

    //认证 springboot 2.1.X可以直接使用
    //密码编码 PasswordEncoder
    //在Spring Secutiry 5.0+ 新增了很多加密方法
    @Override
    protected void configure(AuthenticationManagerBuilder  auth) throws Exception {
        //正常从数据库读
        //开启登录验证功能,roles方法可以实现授权功能,让这个用户登录之后可以获取什么角色权限
        //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
       //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
       //spring security 官方推荐的是使用bcrypt加密方式。
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("tangyu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");

    }
}

实际效果图

刚进来的页面

springboot身份证OCR springbootsecurity 认证_ico_02

登录之后的样子

springboot身份证OCR springbootsecurity 认证_java_03

2.3前端页面操作

在前端页面使用相关语法需要导入命名空间
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>

   <!--如果已登录-->
   <!--sec:authorize="isAuthenticated()语法判断是否认证、授权成功-->
   <div sec:authorize="isAuthenticated()">
       <a class="item">
           <i class="address card icon"></i>
           <!--sec:authentication="principal.username" 获取登录名-->
            <!--sec:authentication="principal.authorities" 获取密码-->
          用户名:<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>
  <!-- sec:authorize="hasRole('vip1')" 判断这个用户是否被授予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>