Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cors exception when posting via '/login' other paths fine #13

Open
gd08xxx opened this issue Jun 26, 2022 · 0 comments
Open

Cors exception when posting via '/login' other paths fine #13

gd08xxx opened this issue Jun 26, 2022 · 0 comments

Comments

@gd08xxx
Copy link

gd08xxx commented Jun 26, 2022

Spring Boot 2.7.0
I faced CORS exception that triggered XMLHttpRequestError when trying to post via the '/login' path, other paths such as '/api/v1/members' are fine.

I am currently using SpringDataRest with configuration in RepositoryRestConfigurer as follow

override fun configureRepositoryRestConfiguration(config: RepositoryRestConfiguration?, cors: CorsRegistry?) {
        cors?.addMapping("/**")?.allowedOriginPatterns("http://localhost:[*]")
    }

Where else do I need to add CORS mapping in order to fulfil the post request via web. Right now posting via mobile app(iOS + Android) is ok with the Flutter framework, but Flutter Web is not ok.

I think the issue might be related to the OncePerRequestFilter? Below is my code from my WebSecurityConfigurerAdapter

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class AppWebSecurityConfigurerAdapter(
    private val passwordEncoder: PasswordEncoder,
    private val appUserDetailsService: AppUserDetailsService,
    private val jwtConfiguration: JwtConfiguration,
    private val secretKey: SecretKey,
    private val repository: MemberRepository
) : WebSecurityConfigurerAdapter() {

    override fun configure(http: HttpSecurity?) { 
        http {
            csrf {
                disable()
            }
            sessionManagement {
                sessionCreationPolicy = SessionCreationPolicy.STATELESS
            }
            addFilterAt<UsernamePasswordAuthenticationFilter>(
                JwtUsernameAndPasswordAuthenticationFilter(
                    authenticationManager(),
                    jwtConfiguration,
                    secretKey,
                    repository
                )
            )
            addFilterAfter<JwtUsernameAndPasswordAuthenticationFilter>(JwtTokenVerifier(jwtConfiguration, secretKey))
            authorizeRequests {
                authorize(anyRequest, permitAll)
            }
        }
    }

    override fun configure(auth: AuthenticationManagerBuilder?) {
        auth?.authenticationProvider(daoAuthenticationProvider())
    }

    @Bean
    fun daoAuthenticationProvider() =
        DaoAuthenticationProvider().apply {
            setPasswordEncoder(passwordEncoder)
            setUserDetailsService(appUserDetailsService)
        }
}

My code for UsernameAndPasswordAuthenticationFilter

class JwtUsernameAndPasswordAuthenticationFilter(
    authenticationManager: AuthenticationManager,
    private val configuration: JwtConfiguration,
    private val secretKey: SecretKey,
    private val repository: MemberRepository
) : UsernamePasswordAuthenticationFilter(authenticationManager) {

    private val objectMapper = jacksonObjectMapper().apply {
        registerModule(JavaTimeModule())
        disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
    }

    override fun attemptAuthentication(request: HttpServletRequest?, response: HttpServletResponse?): Authentication {
        val authenticationRequest: UsernameAndPasswordAuthenticationRequest? =
            request?.inputStream?.let { jacksonObjectMapper().readValue(it) }
        return authenticationManager.authenticate(
            UsernamePasswordAuthenticationToken(authenticationRequest?.username, authenticationRequest?.password)
        )
    }
 
    override fun successfulAuthentication(
        request: HttpServletRequest?,
        response: HttpServletResponse?,
        chain: FilterChain?,
        authResult: Authentication?
    ) {
        val token = Jwts.builder()
            .setSubject(authResult?.name)
            .claim("authorities", authResult?.authorities)
            .setIssuedAt(Date())
            .setExpiration(java.sql.Date.valueOf(LocalDate.now().plusDays(configuration.daysToExpire)))
            .signWith(secretKey)
            .compact()
        val body = objectMapper.writeValueAsString(authResult?.name?.let(repository::findByEmail))
        response?.apply {
            addHeader(configuration.authorizationHeader, "${configuration.tokenPrefix} $token") 
            addHeader(HttpHeaders.CONTENT_TYPE, "application/json;charset=utf-8")
            writer.write(body)
        }
    }
}

App.kt


@SpringBootApplication
@ConfigurationPropertiesScan
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

Much help is appreciated:)

@gd08xxx gd08xxx changed the title Cors exception when adding Cors exception when posting via '/login' other paths fine Jun 26, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant