标签: spring-security

Spring webflux 与 jwt + csrf 令牌

我需要对我的后端实施 CSRF 保护。我正在使用以下配置。但应用程序允许没有 CSRF 令牌的 Post 和 Get 请求。

@Slf4j
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {

    @Bean
    SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        http
                .csrf(csrf -> csrf.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()))
                .authorizeExchange()
                .anyExchange().authenticated()
                .and().oauth2ResourceServer().jwt();
        return http.build();
    }
}
Run Code Online (Sandbox Code Playgroud)

在 HTTP 请求中包含实际的 CSRF 令牌

 @ControllerAdvice
    public class SecurityControllerAdvice {
        @ModelAttribute
        Mono<CsrfToken> csrfToken(ServerWebExchange exchange) {
            Mono<CsrfToken> csrfToken = exchange.getAttribute(CsrfToken.class.getName());
            return csrfToken.doOnSuccess(token -> {
                exchange.getAttributes()
                        .put(CsrfRequestDataValueProcessor.DEFAULT_CSRF_ATTR_NAME, token);
            });
        }
    }
Run Code Online (Sandbox Code Playgroud)

我尝试使用邮递员的API。但这对我不起作用。

春季版

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/>
   </parent> 
Run Code Online (Sandbox Code Playgroud)

依赖项:

<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-resource-server</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
            <version>RELEASE</version>
        </dependency> …
Run Code Online (Sandbox Code Playgroud)

csrf spring-security vue.js spring-webflux

1
推荐指数
1
解决办法
1033
查看次数

响应式 Spring 授权服务器

我正在尝试使用 spring-authorization-server,它似乎工作得很好,但正如我所看到的,它依赖于 servlet api,这使得它不能与 spring webflux 和 netty 一起使用。有谁知道如何解决这个问题?或者如果我的假设是错误的,也许可以纠正我。

谢谢

java spring spring-security oauth-2.0 spring-webflux

1
推荐指数
1
解决办法
1067
查看次数

为什么像 spring-security 这样的 spring boot 库在 /src/main 中有断言,而不是针对此类验证抛出异常?

在浏览 Spring Boot 存储库中的许多模块时,我可以在文件/src/main/中找到如下断言,

public OAuth2AccessToken(TokenType tokenType, String tokenValue, Instant issuedAt, Instant expiresAt,
            Set<String> scopes) {
        super(tokenValue, issuedAt, expiresAt);
        Assert.notNull(tokenType, "tokenType cannot be null");
        this.tokenType = tokenType;
        this.scopes = Collections.unmodifiableSet((scopes != null) ? scopes : Collections.emptySet());
    }
Run Code Online (Sandbox Code Playgroud)

难道不应该使用抛出异常来代替/src/main/.

据我所知,断言旨在与/src/test/.

java spring spring-mvc spring-security spring-boot

1
推荐指数
1
解决办法
56
查看次数

Spring security saml2 提供程序:即使未找到保存的请求,也会执行 saml2 的 InResponseTo 验证

在 spring security saml2 提供程序版本 5.7.x 中,如果在身份验证响应中提供了 InResponseTo,则引入了强制验证。

验证逻辑期望在 HttpSession 中找到保存的 Saml2AuthenticationRequest。但是,只有在未设置 SameSite 属性的情况下,这才有可能。

根据我正在处理的当前项目的安全要求,将其设置为“宽松”或“严格”。此配置是在应用程序外部完成的。这会导致会话和请求数据丢失。

也许有人已经处理过一个问题并且知道如何处理它?我没有看到任何禁用验证的方法或保存库中可用的请求的替代方法。

spring-security saml-2.0

1
推荐指数
1
解决办法
2111
查看次数

Springboot 3 Webflux + Spring Security CSRF 禁用不起作用

今天我将我的 Webflux REST API 演示应用程序从 springboot 升级2.7.x到了 version 3.0.0。在使用 SpringSecurity 测试 POST 调用时,我收到了403 Forbidden消息An expected CSRF token cannot be found。我仔细检查了我的安全配置,没有发现任何问题。

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
            .csrf().disable()
            .authorizeExchange()
            .pathMatchers(HttpMethod.GET, "/actuator/**").permitAll()
            .pathMatchers(HttpMethod.POST, "/api/v1/users", "/api/v1/users/**").hasRole(ReactiveConstant.SECURITY_ROLE_ADMIN)     // Only admin can do POST
            .pathMatchers(HttpMethod.GET, "/api/v1/users", "/api/v1/users/**").hasAnyRole(ReactiveConstant.SECURITY_ROLE_USER, ReactiveConstant.SECURITY_ROLE_ADMIN)       // user can only do GET
            .anyExchange().authenticated()
            .and().formLogin()
            .and().httpBasic()
            .and().formLogin().disable()
            .build();
    }
Run Code Online (Sandbox Code Playgroud)

这适用于 SpringBoot 2.7.5 版本。我的build.gradle文件,

plugins {
    id 'org.springframework.boot' version '3.0.0'
    id 'io.spring.dependency-management' version '1.1.0' …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-boot spring-webflux

1
推荐指数
1
解决办法
2203
查看次数

请求匹配器无法允许允许的路径

我正在按照旧的教程来实现 Spring Security。不幸的是,antMatchers在我的配置类中没有被识别为方法,因此在做了一些研究之后,我相信requestMatchers方法是它的等价物。然而,未经身份验证,路径 ( /) 仍处于阻塞状态。我愿意允许这样做。

这是我的控制器:

package com.quadri.springsecurity.controllers;

import java.util.Arrays;
import java.util.List;

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

import com.quadri.springsecurity.models.Student;

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
        new Student(1, "James Bond"),
        new Student(2, "Maria Jones"),
        new Student(3, "Anna Smith")
    );

    @GetMapping(path = "{studentId}")
    public Student getStudent(@PathVariable("studentId") Integer studentId) {
        return STUDENTS.stream()
        .filter(student -> studentId.equals(student.getStudentId()))
        .findFirst()
        .orElseThrow(() -> new IllegalStateException("Student " + studentId + " does not …
Run Code Online (Sandbox Code Playgroud)

java spring-security spring-boot

1
推荐指数
1
解决办法
6480
查看次数

Feign Client 与 Spring Cloud GatewayFilter 导致循环依赖

在某些检查期间,我需要向网关过滤器中的微服务发出请求。\n当我在 GatewayFilter(my SecurityFilter.java) 类中定义 Feign 类时,会出现以下错误。\n我该如何解决这种情况。

\n

错误:

\n
Description:\n\nThe dependencies of some of the beans in the application context form a cycle:\n\n\xe2\x94\x8c\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x90\n|  securityFilter defined in file [/target/classes/com/example/SecurityFilter.class]\n\xe2\x86\x91     \xe2\x86\x93\n|  cachedCompositeRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]\n\xe2\x86\x91     \xe2\x86\x93\n|  routeDefinitionRouteLocator defined in class path resource [org/springframework/cloud/gateway/config/GatewayAutoConfiguration.class]\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x80\xe2\x94\x98\n\n\nAction:\n\nDespite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.\n
Run Code Online (Sandbox Code Playgroud)\n

网关过滤器类

\n
@Component\npublic class SecurityFilter implements GatewayFilterFactory<SecurityFilter.Config> {\n\n    private final UserApi userApi;\n\n    public SecurityFilter(UserApi …
Run Code Online (Sandbox Code Playgroud)

spring-security spring-boot spring-cloud-feign spring-cloud-gateway openfeign

1
推荐指数
1
解决办法
1792
查看次数

Vaadin 24 种绕过 Spring Security 的资源

对于 Vaadin 14,有文档明确说明应将哪些 Vaadin 资源添加到配置中以绕过 Spring Security: https: //vaadin.com/docs/v14/flow/tutorial/login-and-authentication

  /**
   * Allows access to static resources, bypassing Spring Security.
   */
  @Override
  public void configure(WebSecurity web) {
    web.ignoring().antMatchers(
        // Client-side JS
        "/VAADIN/**",

        // the standard favicon URI
        "/favicon.ico",

        // the robots exclusion standard
        "/robots.txt",

        // web application manifest
        "/manifest.webmanifest",
        "/sw.js",
        "/offline.html",

        // icons and images
        "/icons/**",
        "/images/**",
        "/styles/**",

        // (development mode) H2 debugging console
        "/h2-console/**");
  }
Run Code Online (Sandbox Code Playgroud)

我无法找到 Vaadin 24 的相同信息。

这是我当前的配置:

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);

        web.ignoring().requestMatchers( …
Run Code Online (Sandbox Code Playgroud)

spring-security vaadin vaadin-flow vaadin24

1
推荐指数
1
解决办法
492
查看次数

如何将 Spring MVC 应用程序与具有 OAuth2.0 安全性的 Spring Cloud Gateway 集成?

我有一个 Spring Boot MVC + Thymeleaf 应用程序,它通过 Spring Cloud Gateway 与一堆微服务进行通信。

mvc_app -> gateway -> (service_a, service_b,...)

现在,我想实现基于 OAuth 2 的安全性,并且希望将身份验证过程集中在网关级别。

这意味着:

  1. 如果用户尝试通过网关访问任何资源服务器(service_a、service_b 等)上的安全资源,网关应将用户重定向到 IdP 登录页面。
  2. 身份验证成功后,网关应使用 accessToken 来访问受保护的资源。

这可以通过以下方式实现:

  1. spring-boot-starter-oauth2-client使用适当的提供者/客户端配置将网关设置为 OAuth 2 客户端
  2. 使用TokenRelay过滤器将AccessToken转发到下游resource_servers。

问题:

当您通过网关进行身份验证时,身份验证状态将在网关应用程序级别维护。网关成功验证后,如何发回 AccessToken、IdToken 以便mvc_app进一步请求时使用相同的 AccessToken?

spring-security oauth-2.0 spring-boot spring-cloud-gateway

1
推荐指数
1
解决办法
421
查看次数

java中的URL路径匹配器(Spring)

在我们的应用程序中,我们正在创建不应被某些网址命中的请求过滤器。我们希望能够排除像 spring do witch url patterns 这样的 url,例如:

// register filter in bean
FilterRegistrationBean filterBeanRegistration = new FilterRegistrationBean();
filterBeanRegistration.setFilter(myFilter());
filterBeanRegistration.addInitParameter("excluded", "*/foo/**, */bar/**");
...
Run Code Online (Sandbox Code Playgroud)

并且新的过滤器不会点击像这样的网址domain:8080/aaa/foo/xxxx,domain:8080/bbb/bar/xxxx。

你能告诉我如何用 spring 类或其他简单的方法来做到这一点吗?谢谢指教。

编辑:有一种FilterBeanRegistration#addUrlPatterns(String... urls)方法可以指定网址,但没有任何格式可以说明应该点击哪个网址。为了我们的目的,最好排除一些网址。

java regex spring spring-security pattern-matching

0
推荐指数
1
解决办法
4528
查看次数