Spring Cloud 之Spring-Security

【Spring底层原理高级进阶】【SpringCloud整合Spring Security OAuth2】深入了解 Spring Security OAuth2:底层解析+使用方法+实战 OAuth2(Open Authorization 2.0)是一种用于授权的开放标准协议,用于通过第三方应用程序访问用户在某个服务提供商上存储的资源,而无需共享用户的凭证(例如用户名和密码)。它允许用户授权给第三方应用程序访问受保护的资源,同时确保用户的凭证信息不被直接暴露给第三方应用程序。OAuth2协议的设计目标是简化授权流程和提高安全性,通过委托授权的方式和使用令牌来实现用户和第三方应用程序之间的安全通信。它已成为许多互联网服务提供商和开发者在构建应用程序时常用的授权标准。 阅读详情

Spring Cloud 之Spring-Security

对于Spring-Security首先要明白这么几点:

1、什么是SpringSecurityurity
2、SpringSecurity应用场景
3、SpringBoot整合Security
4、Security formLogin 模式
5、Security httpBasic模式
6、Security 实现账号权限控制
7、Security 自定义登陆界面
8、RBAC权限控制模型
http://pig.pigx.top/#/admin/role

 

什么是SpringSecurityu
Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。
参考百度百科:https://baike.baidu.com/item/spring%20security/8831652?fr=aladdin

SpringSecurity官网:https://spring.io/projects/spring-security
Spring整合SpringSecurityu
SpringBoot整合SpringSecurityu

 

微服务安全框架 SpringBootSecurity
Security应用场景

Security在很多企业中作为后台角色权限框架、授权认证oauth2.0 、安全防护(防止跨站点请求)、Session攻击、非常容易融合SpringMVC使用等

有两个账户
admin 账户 所有请求都有权限访问
userAdd账户 只能访问查询和添加订单权限
403 权限不足
401 没有授权

 

环境搭建:

  admin账户  所有请求都有权限访问

  userAdd账户  只能访问查询和添加订单

  

  关于 formLogin模式   :  表单提交认证模式 

           httpBasic模式   :浏览器与服务器做认证授权

 

  maven的依赖主要:

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

 

关于HttpBasic模式:

  

在HTTP协议进行通信的过程中,HTTP协议定义了基本认证过程以允许HTTP服务器对WEB浏览器进行用户身份证的方法,当一个客户端向HTTP服务 器进行数据请求时,如果客户端未被认证,则HTTP服务器将通过基本认证过程对客户端的用户名及密码进行验证,以决定用户是否合法。客户端在接收到HTTP服务器的身份认证要求后,会提示用户输入用户名及密码,然后将用户名及密码以BASE64加密,加密后的密文将附加于请求信息中, 如当用户名为toov5,密码为:123456时,客户端将用户名和密码用“:”合并,并将合并后的字符串用BASE64加密为密文,并于每次请求数据 时,将密文附加于请求头(Request Header)中。HTTP服务器在每次收到请求包后,根据协议取得客户端附加的用户信息(BASE64加密的用户名和密码),解开请求包,对用户名及密码进行验证,如果用 户名及密码正确,则根据客户端请求,返回客户端所需要的数据;否则,返回错误代码或重新要求客户端提供用户名及密码。

 

maven:

 

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    <!-- 管理依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.M7</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <!-- SpringBoot整合Web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- springboot整合freemarker -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

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


    </dependencies>
    <!-- 注意: 这里必须要添加, 否者各种依赖有问题 -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

Controller:

 

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class OrderController {
    // 首页
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    // 查询订单
    @RequestMapping("/showOrder")
    public String showOrder() {
        return "showOrder";
    }

    // 添加订单
    @RequestMapping("/addOrder")
    public String addOrder() {
        return "addOrder";
    }

    // 修改订单
    @RequestMapping("/updateOrder")
    public String updateOrder() {
        return "updateOrder";
    }

    // 删除订单
    @RequestMapping("/deleteOrder")
    public String deleteOrder() {
        return "deleteOrder";
    }

    // 自定义登陆页面
    @GetMapping("/login")
    public String login() {
        return "login";
    }

}

对于403状态码的错误处理:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ErrorController {

    // 403权限不足页面
    @RequestMapping("/error/403")
    public String error() {
        return "/error/403";
    }

}

 

config:

 权限的配置:  

 对于fromLogin登录页面的修改自定义  关闭csdrf 配置loginpage就OK了

   

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.password.NoOpPasswordEncoder;
import org.springframework.stereotype.Component;

import com.mayikt.handler.MyAuthenticationFailureHandler;
import com.mayikt.handler.MyAuthenticationSuccessHandler;

// Security 配置
@Component
@EnableWebSecurity                  //继承这个类
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private MyAuthenticationFailureHandler failureHandler;
  @Autowired
  private MyAuthenticationSuccessHandler successHandler;
    // 配置认证用户信息和权限
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 添加admin账号
        auth.inMemoryAuthentication().withUser("admin").password("123456").
        authorities("showOrder","addOrder","updateOrder","deleteOrder");
        // 添加userAdd账号
        auth.inMemoryAuthentication().withUser("userAdd").password("123456").authorities("showOrder","addOrder");
        // 如果想实现动态账号与数据库关联 在该地方改为查询数据库
 
    }

    // 配置拦截请求资源
    protected void configure(HttpSecurity http) throws Exception {
        // 如何权限控制 给每一个请求路径 分配一个权限名称 让后账号只要关联该名称,就可以有访问权限
        http.authorizeRequests()
        // 配置查询订单权限
        .antMatchers("/showOrder").hasAnyAuthority("showOrder")
        .antMatchers("/addOrder").hasAnyAuthority("addOrder")
        .antMatchers("/login").permitAll() //登录请求不可以拦截!
        .antMatchers("/updateOrder").hasAnyAuthority("updateOrder")
        .antMatchers("/deleteOrder").hasAnyAuthority("deleteOrder")
        .antMatchers("/**").fullyAuthenticated().and().formLogin().loginPage("/login").  //配置登录页面!!
        successHandler(successHandler).failureHandler(failureHandler)   //成功和失败的配置
        .and().csrf().disable();   //csrf跨站点攻击关闭 否则必须要传递token!!      
    }

    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }

}

  权限相关页面配置:自定义web服务器参数

  

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class WebServerAutoConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400");
        ErrorPage errorPage401 = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401");
        ErrorPage errorPage403 = new ErrorPage(HttpStatus.FORBIDDEN, "/error/403");
        ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404");
        ErrorPage errorPage415 = new ErrorPage(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "/error/415");
        ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500");
        factory.addErrorPages(errorPage400, errorPage401, errorPage403, errorPage404, errorPage415, errorPage500);
        return factory;
    }
}

 

AuthenticationFailureHandler 认证失败接口

AuthenticationSuccessHandler 认证成功接口

 成功和失败的处理:

 失败:

  

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

//认证失败
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse res, AuthenticationException auth)
            throws IOException, ServletException {
        System.out.println("登陆失败!");
        res.sendRedirect("http://baidu.com");

    }

}

成功:

 

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

// 认证成功
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication arg2)
            throws IOException, ServletException {
        System.out.println("用户认证成功");
        res.sendRedirect("/");
    }

}

启动类:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AppSecurity {

    public static void main(String[] args) {
        SpringApplication.run(AppSecurity.class, args);
        // Security 两种模式 fromLogin 表单提交认证模式 httpBasic 浏览器与服务器做认证授权
    }

}

yml:

# 配置freemarker
spring:
  freemarker:
    # 设置模板后缀名
    suffix: .ftl
    # 设置文档类型
    content-type: text/html
    # 设置页面编码格式
    charset: UTF-8
    # 设置页面缓存
    cache: false
    # 设置ftl文件路径
    template-loader-path:
      - classpath:/templates
  # 设置静态文件路径,js,css等
  mvc:
    static-path-pattern: /static/**

 

页面:

 

login.ftl:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <h1>Toov5--权限控制登陆系统</h1>
    <form action="/login" method="post">
        <span>用户名称</span><input type="text" name="username" /> <br>
        <span>用户密码</span><input type="password" name="password" /> <br>
        <input type="submit" value="登陆"> 
    </form>    
<#if RequestParameters['error']??>
用户名称或者密码错误
</#if>
</body>
</html>

 

spring cloud security做统一认证中心 说说在使用spring cloud security微服务统一权限+nuxtjs做前后端分离时,的一些经验吧 在谈之前,我先把spring cloud security的原理罗嗦一遍 Spring cloud security 是包含了spring security 和spring security oauth,这可以算是两个框架。Spring security实现了一组过滤器链,我直接把之前... 阅读详情

相关推荐

【Spring Cloud】:如何使用Spring Security进行身份验证

如果你想要自定义登录页面,可以覆盖默认的表单登录配置,指定自己的HTML页面。formLogin.loginPage("/login") // 自定义登录页面URL.permitAll() // 登录页面无需认证即可访问。

Pmyx_wyh的博客 1267

【SpringCloud】Spring Security简介、快速入门、原理流程

简介、快速入门、登录校验流程、原理初探、认证流程详解

See_Star的博客 2481

微服务动态权限管理方案(Spring Cloud Gateway+Spring Cloud Security)

基于Spring Cloud Gateway和Spring Cloud Security的微服务用户动态权限管理方案

weixin_43349057的博客 2830

Spring Cloud(十二):Spring Cloud Security

设置用户名密码(内存、UserDetailsService、WebSecurityConfigurerAdapter、基于DB) 自定义登录页面 登录认证流程 自定义成功失败 会话管理 会话控制 会话超时 会话并发控制 集群session 安全会话cookie RememberMe 退出登录 CSRF 用户授权 web授权 访问控制的url匹配 内置的访问控制 自定义403处理 基于表达式的访问控制 方法授权 JSR-250注解 @Secured注解 支持表达式的注解 授权原理 授权流程 实现原理 主线源码

Men-DD 4418

便携式水下动态实时视频色彩还原设备,一键快速实现对水下偏色视频和图像的色彩还原处理

便携式水下动态实时视频色彩还原,一键快速对水下图像进行色彩校正,清晰度提升和亮度均衡处理,为水下资源勘探和科学考古,海洋生态环境监测,水下机器作业等应用提供有力的协助

weixin_43518680的博客 633

DDR核心机制解析:从Burst到Prefetch的性能跃迁

本文深入解析了DDR内存性能跃迁的核心机制,重点阐述了Burst(突发传输)与Prefetch(预取)技术的协同工作原理。Burst机制通过连续传输数据减少访问延迟,而Prefetch则通过内部预取数据提升吞吐量,两者结合完美匹配现代CPU缓存行需求,是DDR3等内存实现高效带宽的关键。

weixin_29232121的博客 135

Spring Cloud 之 Spring-Security

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

小尾寒羊的博客 4317

VIVADO网表文件DCP和EDF

为了便于模块化设计,同时保护自己的知识产权,Xilinx VIVADO 提供两种代码封装方法:DCP文件和edf文件。

u014035968的博客 1万+

springcloud集成Spring Security

1.自定义配置类继承WebSecurityConfigurerAdapter配置类2.通过重写方法来定义安全规则和访问控制。通常用于测试或者开发环境中,因为它并不会对密码进行任何加密,而是将密码以明文的形式存储和验证。存在严重的安全风险,因为密码可以很容易地被窃取和滥用。建议不要在生产环境中使用类似的明文密码存储方式。@Bean//这里配置用户信息,这里暂时使用这种方式将用户存储在内存中//获取一个密码编码器对象@Bean//密码为明文方式//配置安全拦截机制@Override。

youxmm的博客 4501

Ethercat学习-从站源码生成

移植平台GD32F450,从站芯片AX58100

西澳峰的博客 9220

压缩包密码破解工具ZIP Cracker2.0.1.2 正式版

一款多功能文件密码破解工具,支持ZIP、RAR、Office等主流加密格式,提供CPU/GPU双模式破解。该软件采用黑客风格界面,具备环境自检修复功能,支持实时监控硬件使用率。内置hashcat等专业破解工具,通过拖拽文件即可快速破解,GPU模式速度可达CPU的10-100倍。最新版本优化了中文路径支持,并提升了启动速度。

bfq05234214的博客 482

Spring Cloud Security

发博词Spring Cloud Security一共有两个starter: org.springframework.cloud spring-cloud-starter-oauth2 org.s

来啊 快活啊 1万+

ConvNeXt 系列改进:引入大核注意力(LKA)替换 7×7 深度卷积,涨点 2.1%

LSKA替换7×7深度卷积,在ImageNet分类任务上实现2.1%的显著提升,参数量仅增加1M。LSKA的四层1D分解将计算复杂度从O(k²)降至O(k),21×21大核的计算量仅相当于原版7×7的1.7倍,实现了感受野与计算成本的完美平衡。部署友好度极高:LSKA模块在TensorRT FP16量化后延迟仅1.2ms,精度损失<0.1%,远优于Transformer类模型。下游任务全面领先。

ZXSXJ的博客 700

spring-cloud-security

基于webflux的spring security,即spring-cloud-security

weixin_39370859的博客 4891

【BlueZ】编译产物详解:可执行文件/库文件/工具的生成路径与用途

BlueZ二次开发编译产物机制解析 摘要:在BlueZ蓝牙协议栈二次开发中,90%的报错源于对编译产物类型和路径的混淆。本文系统剖析BlueZ的三阶段编译机制:1)配置阶段生成Makefile;2)编译阶段在.libs目录下产生临时库和可执行文件(不可直接运行);3)安装阶段将产物部署到系统标准路径。重点解析守护进程、命令行工具、动态库的核心路径差异,并针对五大高频问题(如临时库运行崩溃、动态库不匹配、系统覆盖等)给出解决方案。

byte轻骑兵的技术小窝 1万+

【电路设计】SERDES与pcie

明确通信接口需要达到什么样的数据速率、信号完整性以及系统中各个部件的互相作用。2.

数字人生 4567

Spring Security 与 Spring Cloud Security 的区别与联系

而Spring Cloud Security是基于它的扩展,专门为微服务架构设计,增加了OAuth2集成、单点登录、服务间安全通信等分布式特性。在实际微服务项目中,我们通常在认证中心使用Spring Security处理用户认证,在其他微服务中使用Spring Cloud Security保护API资源,两者协同工作构建完整的安全体系。:说说Spring Security和Spring Cloud Security的区别?资源服务1:Spring Cloud Security。在微服务架构中,二者通常。

weixin_42932609的博客 750

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

Spring Cloud 服务安全 Spring Security

Spring Security 是一套功能全面、扩展性强的安全框架,与 Spring Cloud 的深度集成使其成为微服务架构中的首选安全方案。通过合理的配置和最佳实践,开发者可以轻松实现用户认证、服务授权以及服务间安全通信,为微服务提供强大的安全保障。

Flying_Fish_roe的博客 1024

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

android 蓝牙通讯demo

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

Spring Cloud Gateway及Security认证

  1.Spring Cloud Gateway简介  Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关。网关作为流量的,在微服务系统中有着非常作用,网关常见的功能有路由转发、权限校验、限流控制等作用。  2.创建工程  本文我们采用最新的Spring Cloud 版本“Finchley.SR2”,注意该版本对应S...

bduwps8393的博客 1101

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

spring-cloud-starter-security和spring-cloud-starter-oauth2

之前学过spring-security,最近又在学习spring-cloud-starter-security和spring-cloud-starter-oauth2, 脑子里顿时冒出一个问题: 之前学的spring-security和最近学的spring-cloud-starter-security有什么关系, spring-cloud-starter-security和spring-clou......

qq_30359369的博客 2万+

Spring Cloud Gateway 整合Spring Security

在Security中用户信息需存放在中,是一个接口,可以使用Security已经实现的,也可以实现接口自定义用户信息类。/***/@Data/*** token*//***//***//***//*** location*//***//***//*** 用户名*//*** 账号密码*//*** 权限列表*/@Override@Override@Override/***/@Override。

974

如何用Spring Cloud Security保护你的微服务?

本文介绍了Spring Cloud Security在微服务架构中的核心作用。作为安全防护框架,它通过OAuth2实现授权机制,允许使用令牌替代传统认证方式;借助JWT实现安全信息传输,包含头部、载荷和签名三部分。文章通过代码示例展示了如何配置资源服务器和JWT过滤器,并演示了实际项目中通过添加依赖、配置安全参数以及使用@PreAuthorize注解实现API权限控制的具体方法。Spring Cloud Security构建了微服务的安全防线,其核心组件协同工作,为系统提供可靠的身份验证和授权保障。

万猫学社 1484

Spring Cloud 之 Gateway、Spring Security、Oauth2 的整合

目录1)learn-shop-public-auth(认证中心)1、生成JKS2、添加pom.xml中主要依赖3、添加主要类3.1 目录结构及主要类说明3.2 WebSecurityConfig3.4 JwtTokenEnhancer3.5 CustomUserDetailsService4、添加公钥访问地址5、添加配置文件2)learn-cloud-gateway(资源中心)1、目录结构2、AuthorizationManager3、ResourceServerConfig4、配置文件 源码地址:看这里,

XiaoY的专栏 8228

【Spring】Spring的模块架构与生态圈—Spring Boot、Spring Cloud与Spring Security

Spring Boot是一个基于Spring框架的开源框架,它旨在简化Spring应用的配置和开发过程。通过约定优于配置的原则,Spring Boot使得开发者可以快速上手,减少了大量的样板代码和配置。Spring Cloud是一个用于构建分布式系统的工具集,提供了一系列的解决方案来处理微服务架构中的常见问题,如配置管理、服务发现、负载均衡、断路器等。Spring Security是一个强大且可扩展的安全框架,提供身份验证和授权功能。

thinking_chou的专栏 1339
上一篇: HTTPS
下一篇: RBAC权限控制
Art&Code
博客等级 码龄7年 77粉丝 554原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值