SpringBoot SpringSecurity 介绍(基于内存的验证)

yizhihongxing

SpringBoot 集成 SpringSecurity + MySQL + JWT 附源码,废话不多直接盘
SpringBoot已经为用户采用默认配置,只需要引入pom依赖就能快速启动Spring Security。
目的:验证请求用户的身份,提供安全访问
优势:基于Spring,配置方便,减少大量代码

image

内置访问控制方法

  • permitAll() 表示所匹配的 URL 任何人都允许访问。
  • authenticated() 表示所匹配的 URL 都需要被认证才能访问。
  • anonymous() 表示可以匿名访问匹配的 URL 。和 permitAll() 效果类似,只是设置为 anonymous() 的 url 会执行 filter 链中
  • denyAll() 表示所匹配的 URL 都不允许被访问。
  • rememberMe() 被“remember me”的用户允许访问 这个有点类似于很多网站的十天内免登录,登陆一次即可记住你,然后未来一段时间不用登录。
  • fullyAuthenticated() 如果用户不是被 remember me 的,才可以访问。也就是必须一步一步按部就班的登录才行。

角色权限判断

  • hasAuthority(String) 判断用户是否具有特定的权限,用户的权限是在自定义登录逻辑
  • hasAnyAuthority(String ...) 如果用户具备给定权限中某一个,就允许访问
  • hasRole(String) 如果用户具备给定角色就允许访问。否则出现 403
  • hasAnyRole(String ...) 如果用户具备给定角色的任意一个,就允许被访问
  • hasIpAddress(String) 如果请求是指定的 IP 就运行访问。可以通过 request.getRemoteAddr() 获取 ip 地址

引用 Spring Security

Pom 文件中添加

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-security</artifactId>
</dependency>
点击查看POM代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>vipsoft-parent</artifactId>
        <groupId>com.vipsoft.boot</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>vipsoft-security</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
  
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.3.7</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

运行后会自动生成 password 默认用户名为: user
image

默认配置每次都启动项目都会重新生成密码,同时用户名和拦截请求也不能自定义,在实际应用中往往需要自定义配置,因此接下来对Spring Security进行自定义配置。

配置 Spring Security (入门)

在内存中(简化环节,了解逻辑)配置两个用户角色(admin和user),设置不同密码;
同时设置角色访问权限,其中admin可以访问所有路径(即/*),user只能访问/user下的所有路径。

自定义配置类,实现WebSecurityConfigurerAdapter接口,WebSecurityConfigurerAdapter接口中有两个用到的 configure()方法,其中一个配置用户身份,另一个配置用户权限:

配置用户身份的configure()方法:

SecurityConfig

package com.vipsoft.web.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置用户身份的configure()方法
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中
        auth.inMemoryAuthentication()
                .passwordEncoder(passwordEncoder)
                .withUser("admin")
                .password(passwordEncoder.encode("888"))
                .roles("ADMIN")
                .and()
                .withUser("user")
                .password(passwordEncoder.encode("666"))
                .roles("USER");
    }

    /**
     * 配置用户权限的configure()方法
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //配置拦截的路径、配置哪类角色可以访问该路径
                .antMatchers("/user").hasAnyRole("USER")
                .antMatchers("/*").hasAnyRole("ADMIN")
                //配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面
                .and().formLogin();

    }
}

添加接口测试用


package com.vipsoft.web.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DefaultController {

    @GetMapping("/")
    @PreAuthorize("hasRole('ADMIN')")
    public String demo() {
        return "Welcome";
    }

    @GetMapping("/user/list")
    @PreAuthorize("hasAnyRole('ADMIN','USER')")
    public String getUserList() {
        return "User List";
    }

    @GetMapping("/article/list")
    @PreAuthorize("hasRole('ADMIN')")
    public String getArticleList() {
        return "Article List";
    }
} 

image

原文链接:https://www.cnblogs.com/vipsoft/p/17348599.html

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:SpringBoot SpringSecurity 介绍(基于内存的验证) - Python技术站

(0)
上一篇 2023年4月25日
下一篇 2023年4月27日

相关文章

  • Sprint Boot @RefreshScope使用方法详解

    Spring Boot的@RefreshScope注解 在Spring Boot中,@RefreshScope注解用于实现动态刷新配置。通过使用@RefreshScope注解,可以在应用程序运行时动态地刷新配置,而不需要重启应用程序。 @RefreshScope注解的使用方法 以下是@RefreshScope注解的使用方法: 在需要动态刷新的Bean上添加@…

    Java 2023年5月5日
    00
  • Mysql数据库编码问题 (修改数据库,表,字段编码为utf8)

    当我们在使用MySQL数据库时,可能会遇到中文乱码的问题。这个问题的根源就是MySQL数据库本身的编码问题。如果我们想要避免这种问题的出现,我们需要将数据库、表和字段的编码都设置为utf8编码。 以下是MySQL数据库编码问题的完整攻略: 1. 确定数据库、表和字段的当前编码 使用以下命令查看当前数据库的编码: SHOW CREATE DATABASE da…

    Java 2023年6月16日
    00
  • 使用IDEA创建Web项目并发布到tomcat的操作方法

    下面是使用IDEA创建Web项目并发布到Tomcat的详细攻略。 1. 配置JDK 使用IDEA开发Web项目需要先配置JDK,可以按照以下步骤进行配置: 打开IDEA,选择File > Project Structure > SDKs。 如果已经有JDK,则可以选择已有的JDK,如果没有,则需要添加JDK。选择左上角的“+”按钮,选择JDK安装…

    Java 2023年5月19日
    00
  • Spring.Net在MVC中实现注入的原理解析

    下面是关于“Spring.Net在MVC中实现注入的原理解析”的完整攻略,包含两个示例说明。 Spring.Net在MVC中实现注入的原理解析 在MVC应用程序中,依赖注入(DI)是一种重要的设计模式,可以大大简化应用程序的开发和维护。本文将介绍如何使用Spring.Net实现依赖注入。 依赖注入 1. 添加依赖 首先,我们需要添加以下依赖: <dep…

    Java 2023年5月17日
    00
  • Java实现学生管理系统详解流程

    Java实现学生管理系统详解流程 一、系统需求分析 1.1 系统功能需求 添加学生信息 删除学生信息 修改学生信息 查询学生信息 显示所有学生信息 1.2 系统性能需求 界面友好,操作简单明了 对学生信息进行持久化存储,确保数据不会丢失 查询、添加、删除、修改操作均要快速、正确 二、系统设计 2.1 数据库设计 使用MySQL数据库存储学生信息,设计学生表s…

    Java 2023年5月19日
    00
  • Java Apache Commons报错“ConversionException”的原因与解决方法

    当使用Java的Apache Commons类库时,可能会遇到“ConfigurationException”错误。这个错误通常由以下原因之一起: 配置文件错误:如果配置文件错误,则可能会出现此错误。在这种情况下,需要检查配置文件以解决此问题。 配置项缺失:如果配置项缺失,则可能会出现此错误。在这种情况下,需要检查配置项以解决此问题。 以下是两个实例: 例1…

    Java 2023年5月5日
    00
  • java实现多人聊天系统

    Java实现多人聊天系统需要考虑网络通信、多线程编程以及GUI等方面,下面我将为您提供完整攻略。 一、基本框架设计 1.客户端 客户端的基本框架设计如下: 登录界面:输入用户名和密码进行登录操作; 聊天窗口:展示聊天信息,提供发送聊天内容的输入框和发送按钮; 好友列表:展示当前在线的好友列表,支持选择好友进行私聊。 2.服务器端 服务器需要处理以下事项: 处…

    Java 2023年5月24日
    00
  • Java8时间api之LocalDate/LocalDateTime的用法详解

    Java8时间API之LocalDate/LocalDateTime的用法详解 Java8提供了全新的时间日期API,提供了更好的灵活性和易用性。其中,LocalDate和LocalDateTime是比较常用的类,下面详细讲解它们的用法。 LocalDate LocalDate是纯日期类,不包含时间。它的使用方式如下: // 获取当前日期 LocalDate…

    Java 2023年5月26日
    00
合作推广
合作推广
分享本页
返回顶部