Spring Security - AuthenticationProvider不为每个请求执行

46scxncf  于 2023-06-28  发布在  Spring
关注(0)|答案(1)|浏览(89)

我已经为Firebase创建了一个自定义身份验证提供程序。但是,它不会对每个(任何)请求执行。我放置的断点没有一个在提供者内部被命中,也没有一个在用户服务中被命中。
当提供有效令牌时,对受保护路由的每个请求都返回403错误,而其他路由工作正常。
身份验证提供程序

@Component
class FirebaseAuthenticationProvider(private val userService: UserService): AuthenticationProvider {

    override fun authenticate(authentication: Authentication?): Authentication {
        val token = authentication?.credentials as? String ?: throw BadCredentialsException("No Token Supplied!")
        val decoded = userService.decodeToken(token)

        val uid = decoded.uid
        val email = decoded.email
        val roles = Role
            .claimsToRoles(decoded.claims)
            .map { SimpleGrantedAuthority(it.name) }

        val userDetails = User(uid, email, roles)
        return UsernamePasswordAuthenticationToken(userDetails, token, roles)
    }

    override fun supports(authentication: Class<*>): Boolean {
        return UsernamePasswordAuthenticationToken::class.java.isAssignableFrom(authentication)
    }

}

安全过滤器

@Configuration
class SecurityConfig(private val authenticationProvider: FirebaseAuthenticationProvider) {

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        return http
            .authorizeHttpRequests()
                .requestMatchers("/api/v1/*/create", "/api/v1/*/update", "/api/v1/*/delete").hasAnyRole("EDITOR", "ADMINISTRATOR")
                .requestMatchers("/api/v1/users/**").hasRole("ADMINISTRATOR")
                .anyRequest().permitAll()
            .and()
                .csrf().disable()
                .authenticationProvider(authenticationProvider)
            .build()
    }

}

我在互联网上尝试了许多修复方法,例如使用AuthenticationManager和创建一个bean来提供“FirebaseAuthenticationProvider”,但都无济于事。

cvxl0en2

cvxl0en21#

您应该首先配置提供程序:

@Configuration
class SecurityConfig(private val authenticationProvider: FirebaseAuthenticationProvider) {

    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        return http
            .csrf().disable()
            .authenticationProvider(authenticationProvider)
            .authorizeHttpRequests()
                .requestMatchers("/api/v1/*/create", "/api/v1/*/update", "/api/v1/*/delete").hasAnyRole("EDITOR", "ADMINISTRATOR")
                .requestMatchers("/api/v1/users/**").hasRole("ADMINISTRATOR")
                .anyRequest().permitAll()
            .build()
    }

}

相关问题