SpringBoot 中使用 Spring Security 实现权限授权与认证

Spring Security 简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

  • Spring Security 官网:https://spring.io/projects/spring-security#overview
  • Spring Security 优点:
    • 对身份验证和授权的全面且可扩展的支持
    • 防御会话固定,点击劫持,跨站点请求伪造等攻击
    • Servlet API集成
    • 与Spring Web MVC的可选集成

SpringBoot 集成 Spring Security

1. 实验环境搭建

使用semantic UI 和 jQuery 搭建一个简易的具有三个不同等级的页面,并实现不同页面间的跳转

package cn.mitaowulong.springboot_security2.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("/")
    public String index(){
        return "index";
    }

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

    @RequestMapping("/level1/{id}")
    public String level1(@PathVariable int id){
        String url = "views/level1/"+id;
        return url;
    }

    @RequestMapping("/level2/{id}")
    public String level2(@PathVariable int id){
        String url = "views/level2/"+id;
        return url;
    }

    @RequestMapping("/level3/{id}")
    public String level3(@PathVariable int id){
        String url = "views/level3/"+id;
        return url;
    }
}

SpringBoot 中使用 Spring Security 实现权限授权与认证_第1张图片

2. 实现授权与认证

需要自定义一个config类,并继承WebSecurityConfigurerAdapter类,重写其中的用于权限授权的方法configure(HttpSecurity http) 和 用于权限认证的 configure(AuthenticationManagerBuilder auth)方法,具体见以下代码

package cn.mitaowulong.springboot_security2.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");

        //注销功能
        http.csrf().disable(); //关闭csrf功能,不关闭防跨站攻击则注销失败
        http.logout().logoutSuccessUrl("/"); //注销成功返回首页

        //记住我 参数与前端勾选框的name相对应
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这里Spring Security强制使用一种加密方式
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                //设置root用户能访问所有页面
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                //guest用户只能访问vip1页面
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
    }
}

此时的index.html文件


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>首页title>
    
    <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="stylesheet">
    <link th:href="@{/css/qinstyle.css}" rel="stylesheet">
head>
<body>


<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="@{/}">首页a>

            
            <div class="right menu">
                
                <a class="item" th:href="@{/toLogin}">
                    <i class="address card icon">i> 登录
                a>
                
                <a class="item" th:href="@{/logout}">
                    <i class="address card icon">i> 注销
                a>
            div>
        div>
    div>

    <div class="ui segment" style="text-align: center">
        <h3>Spring Security Studyh3>
    div>

    <div>
        <br>
        <div class="ui three column stackable grid">
            <div class="column">
                <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">
                <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">
                <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>
        div>
    div>
div>
<script th:src="@{/js/jquery-3.1.1.min.js}">script>
<script th:src="@{/js/semantic.min.js}">script>
body>
html>

至此,已经实现权限授权与认证,再次登录,root用户可访问所有页面,guest用户只能访问level1对应的三个页面,当进入其他页面时会被拦截(403错误)
另外,Spring Security 还可与 Thymeleaf 整合
命名空间:

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"

相关依赖:


<dependency>
    <groupId>org.thymeleaf.extrasgroupId>
    <artifactId>thymeleaf-extras-springsecurity4artifactId>
    <version>3.0.2.RELEASEversion>
dependency>

例如可以前端的选择性显示,用户未登录时,显示登陆标签,当用户登录后,则显示注销标签,修改后的前端代码如下
注意(大坑):想实现此功能所使用的的SpringBoot版本最高为2.0.9.RELEASE
SpringBoot 中使用 Spring Security 实现权限授权与认证_第2张图片
如果想实现不同用户对应的权限显示对应的标签,可以如下:
SpringBoot 中使用 Spring Security 实现权限授权与认证_第3张图片
这样就实现了当不同用户登录时显示不同的权限页面,比如现在登录guest用户(只有vip1权限),登录后则会如下:
SpringBoot 中使用 Spring Security 实现权限授权与认证_第4张图片
附:本文中用到的所有Maven依赖

    <dependencies>
        
        <dependency>
            <groupId>org.thymeleaf.extrasgroupId>
            <artifactId>thymeleaf-extras-springsecurity4artifactId>
            <version>3.0.2.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>

        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleaf-spring5artifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.thymeleaf.extrasgroupId>
            <artifactId>thymeleaf-extras-java8timeartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
    dependencies>

你可能感兴趣的:(框架)