Spring Boot安全配置忽略允许的端点

标签 spring spring-boot spring-security jwt

我正在尝试使用 JWT 来获取 Spring Security 来与应用程序一起使用。我读过很多教程和示例,但没有什么真正适合我的用例。我们不通过用户名/密码授权,我们使用 twilio 来验证手机号码,然后我想创建一个简单的 JWT token ,以手机号码作为主题。我已经做到了

这是一个存在于/api/v1/jwt 中的简单端点

@GetMapping("/jwt")
    fun jwt(@RequestParam(value = "number", required = true) number: String): String? {

        val jwtToken = Jwts.builder().setSubject(number).claim("roles", "user").setIssuedAt(Date()).signWith(SignatureAlgorithm.HS256, Base64.getEncoder().encodeToString("secret".toByteArray())).compact()

        return jwtToken

    }

它返回一个有效的 JWT token 。

不过,我的安全配置不再起作用,现在所有端点似乎都受到保护,

@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Bean
    override fun authenticationManagerBean(): AuthenticationManager {
        return super.authenticationManagerBean()
    }

    override fun configure(web: WebSecurity) {
        web.ignoring().antMatchers("/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources/**",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**");
    }

    override fun configure(http: HttpSecurity) {

        http.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/api/v1/auth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(JwtFilter(), UsernamePasswordAuthenticationFilter::class.java)
    }
}

智威汤逊过滤器


    @Throws(IOException::class, ServletException::class)
    override fun doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain) {
        val request = req as HttpServletRequest
        val response = res as HttpServletResponse
        val authHeader = request.getHeader("authorization")
        if ("OPTIONS" == request.method) {
            response.status = HttpServletResponse.SC_OK
            chain.doFilter(req, res)
        } else {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                throw ServletException("Missing or invalid Authorization header")
            }
            val token = authHeader.substring(7)
            try {
                val claims = Jwts.parser().setSigningKey(Base64.getEncoder().encodeToString("secret".toByteArray())).parseClaimsJws(token).body
                request.setAttribute("claims", claims)
            } catch (e: SignatureException) {
                throw ServletException("Invalid token")
            }
            chain.doFilter(req, res)
        }
    }
}

似乎过滤器随时都会受到攻击,无论其上方是否有许可。 任何 api/v1/auth/路径上的过滤器不应该被忽略吗?我想我错过了一些东西。

第二个问题是有没有一种方法可以应用此过滤器,而无需在之前或之后添加并且不扩展 https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.html

编辑:antPathRequestMatcher 没有针对配置触发,但我什至添加了 Websecurity 配置的路径,我得到了此日志记录

2019-12-30 14:44:44.792 DEBUG 81181 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy        : /api/v1/auth/request?number=5555555 has an empty filter list```

最佳答案

在您的配置中,您有:

override fun configure(http: HttpSecurity) {
  http.csrf()
  .disable()
  .sessionManagement()
  .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  .and()
  .authorizeRequests()
  .antMatchers("/api/v1/auth/**").permitAll()
  .anyRequest().authenticated()
  .and()
  .addFilterBefore(JwtFilter(), UsernamePasswordAuthenticationFilter::class.java)
}

我看到以下内容:

.antMatchers("/api/v1/auth/**").permitAll()
.anyRequest().authenticated()

所以 Spring Security 正在检查所有请求的身份验证。 在我的 spring 配置中,我通常这样做:

.antMatchers("/swagger-ui.html","/webjars/**","/swagger-resources/**", "/v2/**","/csrf")
.permitAll()
.antMatchers("/**")
.authenticated()

因此尝试通过设置更改您的配置:

override fun configure(http: HttpSecurity) {
  http.csrf()
  .disable()
  .sessionManagement()
  .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  .and()
  .authorizeRequests()
  .antMatchers("/api/v1/auth/**").permitAll()
  .antMatchers("/**").authenticated()
  .and()
  .addFilterBefore(JwtFilter(), UsernamePasswordAuthenticationFilter::class.java)
}

关于你的第二个问题:

Second question is there a way to apply this filter without having to addbefore or after and not extend https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/web/authentication/AbstractAuthenticationProcessingFilter.html

在这种情况下,老实说,我会使用 spring security 和 spring security oauth sprign security jwt 来转向 OAuth/OpenID。

在本例中,我将创建一个 ResourceServer 配置类和一个 AuthorizationServer 配置类(或者同一个类可以用作 AuthorizationServer 和 ResourceServer);这里有一个很好的例子 https://www.baeldung.com/spring-security-oauth-jwt

希望有用

安杰洛

关于Spring Boot安全配置忽略允许的端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59535223/

相关文章:

java - 如何在 Spring Boot 应用程序中配置 HikariCP 和 Dropwizard/Coda-Hale 指标

java - 如何使用 Spring Integration 动态创建多个 TcpOutboundGateways?

java - Spring Boot with Camel 无法加载应用程序上下文

Spring Rest请求方法 'GET '不支持

java - Spring security @PreAuthorize hasRole() 属性注入(inject)

Spring Web MVC 渲染 View 时存在巨大的性能问题

spring-security - 我可以在Spring应用程序中同时使用GlobalMethodSecurityConfiguration和WebSecurityConfigurerAdapter吗

spring - DefaultJmsListenerContainerFactory 和并发连接未关闭

java - 在spring ioc中定义一个bean之外的集合

java - 如何从 Main 类将属性注入(inject)到 spring bean 中