SpringSecurity:基本用法

SpringSecurity——基本原理 一、Spring Security的理解 Spring Security最核心的是过滤器链,也就是一组过滤器(Filter),所有的访问服务的请求都会经过spring security的过滤器,服务的响应也会经过spring security的过滤器再返回给客户端,并且这些过滤器在系统启动时springboot会自动都配置完成。 二、Spring Security基本原理 1、Spring Security基本原理图解 2、spring security核心过滤器 (1)、UsernamePasswo 阅读详情

一:创建项目与简单实现

  1. 创建一个spring boot项目,倚赖如下:
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

  1. 创建一个简单的接口如下:
package com.example.springsecurity01.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: 洺润Star
 * @Date: 2019/9/19 17:37
 * @Description:
 */
@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "Hello";
    }
}

  1. 访问 http://localhost:8080/hello出现登陆界面,用户名默认为user,密码每次随机生成,启动项目时日志当中会有打印,登陆成功后会返回我们想要的结果

  2. 要想自定义用户名和密码我们可以在application.properties中实现

#下面分别为用户名,密码,和用户的角色
spring.security.user.name=root
spring.security.user.password=root
spring.security.user.roles=admin

二:基于内存的认证

package com.example.springsecurity01.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Auther: 洺润Star
 * @Date: 2019/9/19 18:00
 * @Description: 基于内存的认证配置了两个用户,继承了WebSecurityConfigurerAdapter
 */
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder(){
   		 //不对密码进行加密
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("123").roles("admin")
                .and()
                .withUser("zhang").password("123").roles("user");
    }

}

三:登陆表单详细配置

以下代码配置了三个用户,不同路径所需要用户的权限,登陆(登出)和及其执行成功后的逻辑处理(本处可返回数据,便于前后端分离开发)

package com.example.springsecurity01.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
//@EnableGlobalMethodSecurity(prePostEnabled = true)

@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("root").password("123").roles("ADMIN", "DBA")
                .and()
                .withUser("admin").password("123").roles("ADMIN", "USER")
                .and()
                .withUser("sang").password("123").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //authorizeRequests()方法开启了HttpSecurity配置
        http.authorizeRequests()
                //以下六行配置了访问路径所需要的角色
                .antMatchers("/admin/**")
                .hasRole("ADMIN")
                .antMatchers("/user/**")
                .access("hasAnyRole('ADMIN','USER')")
                .antMatchers("/db/**")
                .access("hasRole('ADMIN') and hasRole('DBA')")
                //下面两行定义了其它url访问必须通过登陆才能访问
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                //登陆界面(自定义的界面)
                //.loginPage("/login_page")
                //登陆处理接口
                .loginProcessingUrl("/login")
                //认证所需的用户名和密码的参数名
                .usernameParameter("name")
                .passwordParameter("passwd")
                //登陆成功的处理逻辑
                .successHandler((req, resp, auth) -> {
                    Object principal = auth.getPrincipal();
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    resp.setStatus(200);
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 200);
                    map.put("msg", principal);
                    ObjectMapper om = new ObjectMapper();
                    out.write(om.writeValueAsString(map));
                    out.flush();
                    out.close();
                })
//                .successForwardUrl("/hello")
                //登陆失败的处理逻辑
                .failureHandler((req, resp, e) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    resp.setStatus(401);
                    Map<String, Object> map = new HashMap<>();
                    map.put("status", 401);
                    if (e instanceof LockedException) {
                        map.put("msg", "账户被锁定,登录失败!");
                    } else if (e instanceof BadCredentialsException) {
                        map.put("msg", "账户名或密码输入错误,登录失败!");
                    } else if (e instanceof DisabledException) {
                        map.put("msg", "账户被禁用,登录失败!");
                    } else if (e instanceof AccountExpiredException) {
                        map.put("msg", "账户已过期,登录失败!");
                    } else if (e instanceof CredentialsExpiredException) {
                        map.put("msg", "密码已过期,登录失败!");
                    } else {
                        map.put("msg", "登录失败!");
                    }
                    ObjectMapper om = new ObjectMapper();
                    out.write(om.writeValueAsString(map));
                    out.flush();
                    out.close();
                })
                .permitAll()
                //注销登陆配置
                .and()
                //开启注销登陆的配置
                .logout()
                //注销登陆请求的URL
                .logoutUrl("/logout")
                //是否清除个人身份认证信息
                .clearAuthentication(true)
                //是否使session失效
                .invalidateHttpSession(true)
                //可添加注销的操作,如cookie的清除
                .addLogoutHandler((req, resp, auth) -> {

                })
                //注销成功之后的业务逻辑,可添加页面的跳转
                .logoutSuccessHandler((req, resp, auth) -> resp.sendRedirect("/login_page"))
                .and()
                .csrf()
                .disable();
    }
}

添加Controller进行测试

package com.example.springsecurity01.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: 洺润Star
 * @Date: 2019/9/19 17:37
 * @Description:
 */
@RestController
public class HelloController {
    @GetMapping("/admin/hello")
    public String admin() {
        return "hello admin!";
    }

    @GetMapping("/admin/db/hello")
    public String admin2() {
        return "/admin/db/hello";
    }

    @GetMapping("/user/hello")
    public String user() {
        return "hello user!";
    }

    @GetMapping("/db/hello")
    public String dba() {
        return "hello dba!";
    }
    
}

四:方法安全

首先要开启基于注解的安全配置

package com.example.springsecurity01.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

/**
 * @Auther: 洺润Star
 * @Date: 2019/9/20 14:34
 * @Description:
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class WebSecurityConfig {
}

开启后即可在service层进行配置,添加注解后即可对方法的调用进行权限控制

package com.example.springsecurity01.service;

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

/**
 * @Auther: 洺润Star
 * @Date: 2019/9/20 14:40
 * @Description:
 */
@Service
public class MethodService {
    //表示需要ADMIN权限(注意要加前缀ROLE_)
    @Secured("ROLE_ADMIN")
    public String admin() {
        return "hello admin";
    }
    //需要ADMIN和DBA两种权限
    @PreAuthorize("hasRole('ADMIN') and hasRole('DBA')")
    public String dba() {
        return "hello dba";
    }
    //表示需要ADMIN或DBA或USER
    @PreAuthorize("hasAnyRole('ADMIN','DBA','USER')")
    public String user() {
        return "user";
    }
}

SpringSecurity 快速入门 在互联网中,我们每天都会使用到各种各样的APP和网站,在使用过程中通常还会遇到需要注册登录的情况,输入你的用户名和密码才能正常使用,也就是说成为这个应用的合法身份才可以访问应用的资源,这个过程就是认证。认证是为了保护系统的隐私数据与资源,用户的身份合法方可访问该系统的资源。当然认证的方式有很多,常见的账号密码登录,手机验证码登录,指纹登录,刷脸登录等等。简单说: 认证就是让系统知道我们是谁。如何实现授权? 阅读详情

相关推荐

springsecurity详细解析

进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付宝、头条,抖音等,下边拿微信来举例子说明认证相关的基本概念,在初次使用微信前需要注册成为微信用户,然后输入账号和密码即可登录微信,输入账号和密码登录微信的过程就是认证。系统为什么要认证?认证是为了保护系统的隐私数据与资源,用户的身份合法,方可访问该系统的资源。认证︰用户认证就是判断一个用户的身份是否合法的过程,用户去访问系统资源时,系统要求验证用户的身份信息,身份合法方可继续访问,不合法则拒绝访问。

m0_65224643的博客 1422

Springboot自动装配的实现流程

带着这个问题到网上搜索,大多数文章在解释这个问题的时候,上来就是@SpringBootApplication注解中找@EnableAutoConfiguration注解,然后找到@Import(AutoConfigurationImportSelector.class)注解,然后就到AutoConfigurationImportSelector类中找,惊呆????~ 不过也没错,最后确实是因为这个注解这个类完成的自动装配,但是Spring是如何从开始的注解一步一步完成自动装配的呢? 接下来一步一步的调试跟

cocoawork 丶的博客 1066

SpringSecurity加密

相对于md5加密,SpringSecurity加密有一定的优势,参考md5加密这一篇文章: 做一些配置的修改,实现SpringSecurity加密 1.修改spring-security.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.

IT_LD的博客 605

Security之注解篇

1.开启基于方法的安全认证机制 2.自定义实现细粒度的权限控制

qq_43654581的博客 1325

SpringSecurity6 | 初始SpringSecurity

大家好,我是Leo哥🫣🫣🫣,今天这个专栏我们一起来学习的系列知识。此次从零开始学习SpringSecurity的概念的和新的写法。带大家SpringSecurity从基础到精通。好了,话不多说让我们开始吧😎😎😎。是一个基于 Spring 框架的安全框架,用于在 Java 应用程序中实现身份认证和授权控制。它提供了一套全面的安全服务,可以用于保护 Web 应用程序、RESTful 服务和方法级别的安全性。验证用户的身份,并确定用户是否具有访问系统资源的权限。

分享思想,留下痕迹。 1万+

SpringSecurity实战

和Shiro相比,Spring Security重量级并且配置烦琐,直至今天,依然有人以此为理由而拒绝了解Spring Security。还拿微信来举例子,微信登录成功后用户即可使用微信的功能,比如,发红包、发朋友圈、添加好友等,没有绑定银行卡的用户是无法发送红包的,绑定银行卡的用户才可以发红包,发红包功能、发朋友圈功能都是微信的资源即功能资源,用户拥有发红包功能的权限才可以正常使用发送红包功能,拥有发朋友圈功能的权限才可以使用发朋友圈功能,这个根据用户的权限来控制用户使用资源的过程就是授权。

2402_83415279的博客 4512

自定义实现@Security进行权限控制

@Security注解实现前言@Security改造handler类改造DispatherServlet测试 前言 在上一篇博客中,我们自定义实现了一个mvc框架,那么现在我们在此基础上,通过注解的方式添加一个权限的控制。 这个注解用于添加在Controller类或者是handler方法上,通过给注解value赋值,表明这个controller或者handler有哪些用户是可以有权限访问的。 其中如果只给controller类添加该注解,表示这个controller类里面所有的方法都可以被该注解声明的用户访

HaiYun 371

(二)目标检测之 HOG+SVM 算法

文章目录一、概述二、方法概述三、积分图四、AdaBoost五、级联检测六、结果七、复现八、总结参考资料 一、概述   梯度直方图HOG(Histogram of Oriented Gradients)是法国人Dalal在2005年CVPR会议上提出的特征提取算法,并将其与 SVM 配合,用于行人检测。论文地址:Histograms of oriented gradients for human detection HOG有个优点,提取的边缘和梯度特征能很好的抓住局部形状的特点,且因是对图像做了Gamma

天青如水的博客 1万+

Spring——Security安全框架之注解使用

文章目录前言本次测试注解介绍注解使用@Secured@PreAuthorize@PostAuthorize@PostFilter@PreFilter代码下载 前言 之前security中,针对配置项进行了相关的配置和测试。 但是这些都是基于在security.config.MyConfig#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)中进行对应请求的权限限制。 如果是多个请求,各个有

专注写bug 5972

手把手教你逆向京东搜索接口:H5ST 556位参数生成与V8补环境技巧

本文深入解析了京东搜索接口中关键的H5ST 556位参数生成机制,并提供了详细的逆向实战指南。针对其复杂的反爬虫环境检测,文章重点介绍了通过链式补环境技巧,在Node.js中完整模拟浏览器环境(包括原型链检测和指纹验证)的方法,帮助开发者成功绕过防护并生成有效参数。

weixin_29315091的博客 481

【谷粒商城】分布式事务与下单

=购物车== 构建gulimall-cart,复制静态资源到nginx,修改网关 购物车分为离线购物车和登录购物车 离线购物车重启浏览器了也还有 1、购物车需求 特点:读多写少,放入数据库并不合适 登录状态:登录购物车 放入数据库 mongodb 放入redis(采用) 登录以后,将离线购物车里合并后清空离线购物车 未登录状态:离线购物车 放入localstorage浏览器的技术 cookie WebSQL 放入redis(采用) 浏览器重启后还在 2、购物车VO (1) 数据结构分析

努力充实,远方可期 1万+

Spring Security中<@security.authorize的使用

系统使用Spring Security登录验证时会把用户的角色信息也带入,例如用户以管理员的帐号登录时角色为ROLE_ADMIN,这时可以利用 首先引入依赖          org.springframework.security          spring-security-taglibs          3.1.4.RELEASE    

xiaosongwahaha的博客 1867

双轴按键摇杆模块原理与嵌入式驱动实战

双轴按键摇杆是一种融合模拟量(X/Y轴)与数字量(Z轴按键)的复合型人机交互传感器,其本质基于电位器分压原理与机械开关通断特性。通过ADC采集连续电压信号并结合数字IO检测按键状态,可实现高鲁棒性的二维运动感知与触发控制。该方案技术门槛低、成本可控、兼容性强,广泛应用于智能小车、DIY游戏手柄、工业HMI及教育开发板等嵌入式场景。文中深入解析电位器线性度、KEY引脚开漏特性、ADC参考电压稳定性及软件消抖状态机等关键工程要素,为基于Arduino、STM32或ESP32平台的快速集成提供可复用的技术路径。

weixin_30995917的博客 82

SpringSecurity是什么,如何学习SpringSecurity?

SpringSecurity是什么,如何学习SpringSecurity?

杨荧的优快云博客 1692

oracle合并行---解决listagg 拼接字段返回过长 (Ora-01489 result of String concatenation is too long)

oracle合并行---解决listagg 拼接字段返回过长 (Ora-01489 result of String concatenation is too long)

清影的博客 6281

Open3D 点云重叠区域检测【2025最新版】

本文介绍了一种基于八叉树和KD树的点云重叠区域检测方法。算法提供两种检测模式:八叉树(快速)和KD树(精确),支持可视化显示和详细统计信息输出。实现功能包括边界扩展、索引去重、精度调节等,可通过max_depth参数控制八叉树细分程度,distance_threshold调整检测精度。代码使用Open3D库,能自动计算并显示各点云的重叠比例和点数统计,最终结果以不同颜色区分重叠与非重叠区域。该方案适用于三维点云数据处理中的重叠分析任务。

点云侠的博客 599

SpringSecurity之——SpringBoot整合SpringSecurity

一、创建工程 新建Maven工程springsecurity-demo,并编辑pom.xml文件如下: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XML...

冰河的专栏 1475

01-诊断开发流程概述

传送门 ==>> AutoSAR入门和实战系列总目录。

1785

SpringSecurity

进入移动互联网时代,大家每天都在刷手机,常用的软件有微信、支付宝、头条等,下边拿微信来举例子说明认证相关的基本概念,在初次使用微信前需要注册成为微信用户,然后输入账号和密码即可登录微信,输入账号和密码登录微信的过程就是认证。系统为什么要认证?认证是为了保护系统的隐私数据与资源,用户的身份合法方可访问该系统的资源。认证:用户认证就是判断一个用户的身份是否合法的过程,用户去访问系统资源时系统要求验证用户的身份信息,身份合法方可继续访问,不合法则拒绝访问。

2301_76557773的博客 867

GEE:哨兵时间序列遥感数据和动态阈值方法计算物候时期EOS/SOS(2)

本文将分享和解释论文《Improved Estimates of Arctic Land Surface Phenology Using Sentinel-2 Time Series》中使用到的基于阈值估算北极地区的植被物候,特别是北极地区的植被季节开始和结束的日期(SoS和EoS)的方法和代码。该方法使用的是使用哨兵2数据,并实现了两种阈值方法( 无平滑的阈值方法、平滑后的阈值方法)。

养乐多的博客 2971

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

SpringSecurity入门

Spring 是非常流行和成功的 Java 应用开发框架,Spring Security 正是 Spring 家族中的成员。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。

m0_62946761的博客 3395

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

SpringSecurity 实战项目(一)

文章目录SpringSecurity 验证帐号密码security认证过程:[《Spring Security认证过程》](https://blog.csdn.net/weixin_38927257/article/details/102960752) 本文使用springboot+mybatis+SpringSecurity 实现用户权限数据库管理 实现用户和角色用数据库存储,而资源(url)和...

weixin_38927257的博客 5769

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

springSecurity

1.SpringSecurity 快速入门 1.1 Spring Security介绍 ​ Spring Security 的前身是 Acegi Security ,是 Spring 项目组中用来提供安全认证服务的框架。(https://projects.spring.io/spring-security/) Spring Security 为基于J2EE企业应用软件提供了全面安全服务。特别是使用领先的J2EE解决方案-Spring框架开发的企业软件项目。人们使用Spring Security有很多

shejiataoBlog 2376

SpringSecurity框架用法简介

目录1. SpringSecurity 框架用法简介2. 权限管理过程中的相关概念2.1 主体2.2 认证2.3 授权3. 权限管理的主流框架3.1 SpringSecurity3.2 Shiro4. 使用配置类代替 XML 配置文件4.1 @Configuration 注解4.2 @Bean 注解5. HelloWorld 工程创建步骤5.1 创建 Maven 的 Web 工程5.2 加入 SpringMVC 环境需要的依赖5.3 创建 SpringMVC 配置文件5.4 在 web.xml 中配置 Di

Criven的博客 413
上一篇: Spring示例:第一个AOP
下一篇: 从零搭建:使用Mycat进行切割数据库
金心靖晨
博客等级 码龄9年 460粉丝 211原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值