Skip to content

Commit

Permalink
fix: add jwt exception filter
Browse files Browse the repository at this point in the history
  • Loading branch information
2paperstar committed Aug 31, 2024
1 parent f26a3be commit af047bf
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package me.gistory.newbies_server_24.configurations

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import me.gistory.newbies_server_24.exceptions.UnauthorizedException
import org.springframework.http.HttpStatus
import org.springframework.web.filter.OncePerRequestFilter

class JwtExceptionFilter : OncePerRequestFilter() {

override fun doFilterInternal(
request: HttpServletRequest,
response: HttpServletResponse,
filterChain: FilterChain
) {
try {
filterChain.doFilter(request, response)
} catch (e: UnauthorizedException) {
response.status = HttpStatus.UNAUTHORIZED.value()
response.contentType = "application/json"
response.writer.write("{\"message\": \"Unauthorized\"}")
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import org.springframework.web.filter.GenericFilterBean
class JwtFilter(private val tokenProvider: TokenProvider) : GenericFilterBean() {
override fun doFilter(req: ServletRequest, res: ServletResponse, chain: FilterChain) {
val request = req as HttpServletRequest
val token = resolveToken(request)
token?.let {
val token = resolveToken(request) ?: throw UnauthorizedException()
token.let {
if (!tokenProvider.validateToken(it)) throw UnauthorizedException()
tokenProvider.getAuthentication(it).let { authentication ->
SecurityContextHolder.getContext().authentication = authentication
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ class SecurityConfiguration {
}
.authorizeHttpRequests { req ->
req.requestMatchers(HttpMethod.GET).permitAll()
req.requestMatchers("/swagger-ui/**" , "v3/api-docs/**", "/api-docs/**").permitAll()
req.requestMatchers("/swagger-ui/**", "v3/api-docs/**", "/api-docs/**").permitAll()
req.requestMatchers("/auth/login", "/auth/register", "auth/refresh").permitAll()
req.requestMatchers("/error").permitAll()
req.requestMatchers("/").permitAll()
req.anyRequest().authenticated()
}
.addFilterBefore(JwtFilter(tokenProvider), UsernamePasswordAuthenticationFilter::class.java)
.addFilterBefore(JwtExceptionFilter(), JwtFilter::class.java)
.build()


Expand Down

0 comments on commit af047bf

Please sign in to comment.