首页 > 系统相关 >SpringBoot SpringSecurity 介绍(基于内存的验证)

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

时间:2023-04-27 09:01:49浏览次数:52  
标签:SpringBoot boot 用户 springframework SpringSecurity 内存 import org security

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

标签:SpringBoot,boot,用户,springframework,SpringSecurity,内存,import,org,security
From: https://www.cnblogs.com/vipsoft/p/17348599.html

相关文章

  • SpringBoot 集成 SpringSecurity + MySQL + JWT 附源码,废话不多直接盘
    SpringBoot集成SpringSecurity+MySQL+JWT无太多理论,直接盘一般用于Web管理系统可以先看SpringBootSpringSecurity基于内存的使用介绍本文介绍如何整合SpringSecurity+MySQL+JWT数据结构数据库脚本:https://gitee.com/VipSoft/VipBoot/blob/develop/vipsoft-sec......
  • SpringBoot配置MongoDb
    MongoDb建表:MongoDB不需要建表,直接插入数据就会建表。日期用ISODate()转换。db.getCollection("mongoDbTest").insert({userId:"dxcefg",status:1,price:1.23,updateTime:ISODate("2022-02-13T07:06:25.371Z")})添加maven依赖:<dependency>......
  • 音视频八股文(6)-- ffmpeg大体介绍和内存模型
    播放器框架常用音视频术语•容器/文件(Conainer/File):即特定格式的多媒体文件,比如mp4、flv、mkv等。•媒体流(Stream):表示时间轴上的一段连续数据,如一段声音数据、一段视频数据或一段字幕数据,可以是压缩的,也可以是非压缩的,压缩的数据需要关联特定的编解码器(有些码流音频他是纯PCM)......
  • 09 管理内存对象
    建立内存页面管理器:既可以分配单个页面,也可以分配多个连续的页面,还能指定在特殊内存地址区域中分配页面;但是这种分配至少是一个页面4KB大小,无法分配一个小于单页大小的内存;malloc函数启发:内存对象:设计:页基础上进行细分,分成32字节、64、128、256、512、1024、2048、4096字节......
  • Java对象内存布局
    一、对象在堆内存中布局Objectobject=newObject()一般而言JDK8按照默认情况下,new一个对象占多少内存空间在HotSpot虚拟机里,对象在堆内存中的存储布局可以划分为三个部分:对象头(Header)、实例数据(InstanceData)和对齐填充(Padding)。二、对象在堆内存中的存储布局下面......
  • springboot自定义拦截器
    springboot自定义拦截器操作说明1、编写一个拦截器实现HandlerInterceptor接口2、拦截器注册到容器中(实现WebMvcConfigures的addInterceptors)3、指定拦截规则(如果是拦截所有,静态资源也会被拦截)LoginInterceptor.javapackagecom.example.springtxiangmu.interceptor;im......
  • Redis内存淘汰策略
    Redis内存淘汰策略是指Redis用于缓存的内存不足时,怎么处理需要新写入且需要申请额外空间的数据 全局的键空间选择性移除noeviction:当内存不足以容纳新写入数据时,新写入操作会报错allkeys-lru:当内存不足以容纳新写入数据时,在键空间中移除最近最少使用的keyallkeys-random:当内......
  • SpringSecurity从入门到精通:认证成功处理器&认证失败处理器
    认证成功处理器  认证失败处理器  ......
  • Django 查询数据库不释放内存的情况
    查询结果未及时清空如果查询结果较大,可能会占用很多内存。在使用完查询结果后,应该及时清空,以释放占用的内存。可以通过将查询结果赋值给一个变量,然后使用del关键字删除变量来清空查询结果。例如:result=MyModel.objects.all()#使用查询结果...#清空查询结果delresul......
  • Unity内存浅谈一
    Unity主要使用的还是c#,就先从这里写写吧.Net内存管理机制主要还是分为托管堆内存和非托管内存。 .Net托管堆内存管理主要的核心思想就是,你只管制造垃圾,它自己会帮你回收垃圾,因为自己是无法回收自己制造的垃圾的,必须依靠它的垃圾回收机制。托管堆主要的内存产生方式就是new一......