-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
✨ added jwtAuthenticationFilter, UserPrincipal, and edited UserAccess…
…TokenUtil, UserService, and SecurityConfig to correctly authenticate social users via jwt
- Loading branch information
Showing
5 changed files
with
152 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,48 @@ | ||
package com.toyProject7.karrot | ||
|
||
import com.toyProject7.karrot.security.JwtAuthenticationFilter | ||
import com.toyProject7.karrot.socialLogin.handler.CustomAuthenticationSuccessHandler | ||
import com.toyProject7.karrot.socialLogin.service.SocialLoginUserService | ||
import org.springframework.context.annotation.Bean | ||
import org.springframework.context.annotation.Configuration | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity | ||
import org.springframework.security.config.http.SessionCreationPolicy | ||
import org.springframework.security.web.SecurityFilterChain | ||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter | ||
|
||
@Configuration | ||
class SecurityConfig { | ||
@EnableWebSecurity | ||
class SecurityConfig( | ||
private val socialLoginUserService: SocialLoginUserService, | ||
private val customAuthenticationSuccessHandler: CustomAuthenticationSuccessHandler, | ||
private val jwtAuthenticationFilter: JwtAuthenticationFilter | ||
) { | ||
|
||
@Bean | ||
fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { | ||
return http | ||
.csrf { csrf -> csrf.disable() } | ||
.sessionManagement { session -> | ||
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS) | ||
} | ||
.authorizeHttpRequests { registry -> | ||
registry.requestMatchers("/", "/login").permitAll() | ||
registry.anyRequest().authenticated() | ||
registry | ||
.requestMatchers( | ||
"/", "/login", "/css/**", "/js/**", "/images/**", "/oauth2/**" | ||
).permitAll() | ||
.anyRequest().authenticated() | ||
} | ||
.oauth2Login { oauth2login -> | ||
oauth2login | ||
.loginPage("/login") | ||
.successHandler { request, response, authentication -> | ||
response.sendRedirect("/profile") | ||
.userInfoEndpoint { userInfo -> | ||
userInfo.userService(socialLoginUserService) | ||
} | ||
.successHandler(customAuthenticationSuccessHandler) | ||
.failureUrl("/login?error=true") | ||
} | ||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java) | ||
.build() | ||
} | ||
} | ||
} |
55 changes: 55 additions & 0 deletions
55
src/main/kotlin/com/toyProject7/karrot/security/JwtAuthenticationClass.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package com.toyProject7.karrot.security | ||
|
||
import com.toyProject7.karrot.user.UserAccessTokenUtil | ||
import com.toyProject7.karrot.user.service.UserService | ||
import jakarta.servlet.FilterChain | ||
import jakarta.servlet.http.HttpServletRequest | ||
import jakarta.servlet.http.HttpServletResponse | ||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken | ||
import org.springframework.security.core.context.SecurityContextHolder | ||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource | ||
import org.springframework.stereotype.Component | ||
import org.springframework.web.filter.OncePerRequestFilter | ||
|
||
@Component | ||
class JwtAuthenticationFilter( | ||
private val userService: UserService | ||
) : OncePerRequestFilter() { | ||
|
||
override fun doFilterInternal( | ||
request: HttpServletRequest, | ||
response: HttpServletResponse, | ||
filterChain: FilterChain | ||
) { | ||
val authHeader = request.getHeader("Authorization") | ||
|
||
if (authHeader != null && authHeader.startsWith("Bearer ")) { | ||
val token = authHeader.substring(7) | ||
|
||
try { | ||
// Validate the token | ||
if (UserAccessTokenUtil.validateToken(token)) { | ||
// Get user ID from token | ||
val userId = UserAccessTokenUtil.getUserIdFromToken(token) | ||
|
||
// Load user details | ||
val userDetails = userService.loadSocialUserById(userId) | ||
|
||
// Create authentication token | ||
val authentication = UsernamePasswordAuthenticationToken( | ||
userDetails, null, userDetails.authorities | ||
) | ||
authentication.details = WebAuthenticationDetailsSource().buildDetails(request) | ||
|
||
// Set the authentication in the context | ||
SecurityContextHolder.getContext().authentication = authentication | ||
} | ||
} catch (e: Exception) { | ||
// Handle exceptions (e.g., log them) | ||
println("Failed to authenticate user: ${e.message}") | ||
} | ||
} | ||
|
||
filterChain.doFilter(request, response) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
src/main/kotlin/com/toyProject7/karrot/user/persistence/UserPrincipal.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package com.toyProject7.karrot.user.persistence | ||
|
||
import org.springframework.security.core.GrantedAuthority | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority | ||
import org.springframework.security.core.userdetails.UserDetails | ||
|
||
data class UserPrincipal( | ||
val id: String, | ||
private val email: String, | ||
private val password: String?, | ||
private val authorities: Collection<GrantedAuthority> | ||
) : UserDetails { | ||
|
||
companion object { | ||
fun create(user: UserEntity): UserPrincipal { | ||
val authorities = listOf(SimpleGrantedAuthority("ROLE_USER")) | ||
|
||
return UserPrincipal( | ||
id = user.id!!, | ||
email = user.email, | ||
password = null, // Password can be null for social login | ||
authorities = authorities | ||
) | ||
} | ||
} | ||
|
||
override fun getAuthorities(): Collection<GrantedAuthority> = authorities | ||
override fun getPassword(): String? = password | ||
override fun getUsername(): String = email | ||
override fun isAccountNonExpired(): Boolean = true | ||
override fun isAccountNonLocked(): Boolean = true | ||
override fun isCredentialsNonExpired(): Boolean = true | ||
override fun isEnabled(): Boolean = true | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters