我的项目中有一个 oauth 流程。
我在前端检索了一个 jwt 令牌并将其添加到授权标头中的每个请求中。
现在我需要验证所述令牌并验证我后端的签名,这是一个 kotlin spring boot 应用程序。
我知道如何使用 jjwt 库验证令牌,但我不明白验证在哪里完成。
我有一个证书来验证令牌,只是想让带有有效令牌的请求得到处理。
我在网上看到有些人使用曾经添加到 SecurityConfiguration 中的 OncePerRequestFilter 来实现,但我不明白发生了什么以及它是如何工作的。
我尝试在线搜索教程,但其中许多教程都制作了既是授权服务器又是资源服务器的后端。我只希望后端是资源服务器,它检查证书是否有效,如果有效则处理请求。我该怎么做?
现在这是我的安全配置:
package com.renaulttrucks.transfertprotocolbackend.security.config
import org.springframework.beans.factory.annotation.Value
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
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
@Value("\${security.enabled}")
val securityEnabled : Boolean? = false
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
if(!securityEnabled!!) {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.and()
.csrf().disable()
.formLogin().disable()
} else {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/**").permitAll()
.and()
.csrf().disable()
.formLogin().disable()
}
}
}
答案 0 :(得分:0)
当包含正确的依赖项和配置时,Spring Security 支持开箱即用的资源服务器。
正如@sdoxsee 所提到的,有一个 Spring Security 示例概述了如何create a resource server with a public key;不过,我将在此处对其进行简要总结,不过您可以在 Spring Security reference 中找到更多详细信息。
首先,您需要添加相应的依赖项。如果你是 Spring Boot 应用,那么你可以添加:
<link rel="shortcut icon" href="{% static 'players/images/liverpool.png' type='image/png' %}"/>
其次,您可以将密钥指定为 Boot 属性:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
或者,您直接使用您的公钥配置 spring:
security:
oauth2:
resourceserver:
jwt:
public-key-location: classpath:my-key.pub
:
JwtDecoder
Boot 属性或 @Configuration
class SecurityConfig {
@Value("${public.key.property}") val key : RSAPublicKey;
@Bean
fun jwtDecoder() : JwtDecoder {
return NimbusJwtDecoder.withPublicKey(this.key).build();
}
}
JwtDecoder
会自动将过滤器引入名为 @Bean
的过滤器链中,因此您无需创建自己的过滤器。