Skip to content

Commit

Permalink
added /api/me and /login/provider end points + fixed securityConfig s…
Browse files Browse the repository at this point in the history
…o after successfully logging in via social login the user is redirected to frontend
  • Loading branch information
jafacode committed Jan 8, 2025
1 parent 5b9ba59 commit 3c1c44a
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 15 deletions.
4 changes: 1 addition & 3 deletions src/main/kotlin/com/toyProject7/karrot/SecurityConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,16 @@ class SecurityConfig(
.authorizeHttpRequests { registry ->
registry
.requestMatchers(
"/", "/login", "/css/**", "/js/**", "/images/**", "/oauth2/**"
"/api/auth/**", "oauth2/**"
).permitAll()
.anyRequest().authenticated()
}
.oauth2Login { oauth2login ->
oauth2login
.loginPage("/login")
.userInfoEndpoint { userInfo ->
userInfo.userService(socialLoginUserService)
}
.successHandler(customAuthenticationSuccessHandler)
.failureUrl("/login?error=true")
}
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter::class.java)
.build()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,38 @@
package com.toyProject7.karrot.socialLogin.service

import com.toyProject7.karrot.user.persistence.UserPrincipal
import org.springframework.http.ResponseEntity
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.security.Principal

@RestController
class MainController {
class SocialLoginController {

@RequestMapping("/")
fun home(): String {
return "Home"
// Endpoint to initiate OAuth2 login for a specific provider
@GetMapping("/api/social/login/{provider}")
fun socialLogin(@PathVariable provider: String): ResponseEntity<Map<String, String>> {
val redirectUrl = "/oauth2/authorization/$provider"
val responseBody = mapOf("redirectUrl" to redirectUrl)
return ResponseEntity.ok(responseBody)
}

@RequestMapping("/user")
fun user(principal: Principal): Principal {
return principal
@GetMapping("/api/social/me")
fun getCurrentUser(@AuthenticationPrincipal userPrincipal: UserPrincipal?): ResponseEntity<Any> {
if (userPrincipal == null) {
return ResponseEntity.status(401).body("Unauthorized")
}

// Build a response with user details
val response = mapOf(
"id" to userPrincipal.id,
"email" to userPrincipal.username,
"name" to userPrincipal.getNickname()
)

return ResponseEntity.ok(response)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import org.springframework.security.oauth2.client.authentication.OAuth2Authentic
import org.springframework.security.oauth2.core.user.OAuth2User
import org.springframework.security.web.authentication.AuthenticationSuccessHandler
import org.springframework.stereotype.Component
import org.springframework.web.util.UriComponentsBuilder

@Component
class CustomAuthenticationSuccessHandler(
Expand All @@ -36,11 +37,13 @@ class CustomAuthenticationSuccessHandler(
// Generate JWT
val accessToken = UserAccessTokenUtil.generateAccessToken(user.id)

// Send the JWT in the response body as JSON
val responseBody = mapOf("accessToken" to accessToken, "user" to user)
response.contentType = "application/json"
response.characterEncoding = "UTF-8"
response.writer.write(ObjectMapper().writeValueAsString(responseBody))
// Redirect to frontend with JWT included in URL fragment
val redirectUri = UriComponentsBuilder.fromUriString("https://your-frontend-domain.com/oauth2/redirect")
.fragment("token=$accessToken")
.build()
.toUriString()

response.sendRedirect(redirectUri)
}

private fun extractProviderId(attributes: Map<String, Any>, provider: String): String {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import org.springframework.security.core.userdetails.UserDetails
data class UserPrincipal(
val id: String,
private val email: String,
private val nickname: String,
private val password: String?,
private val authorities: Collection<GrantedAuthority>
) : UserDetails {
Expand All @@ -18,6 +19,7 @@ data class UserPrincipal(
return UserPrincipal(
id = user.id!!,
email = user.email,
nickname = user.nickname,
password = null, // Password can be null for social login
authorities = authorities
)
Expand All @@ -26,6 +28,7 @@ data class UserPrincipal(

override fun getAuthorities(): Collection<GrantedAuthority> = authorities
override fun getPassword(): String? = password
fun getNickname(): String = nickname
override fun getUsername(): String = email
override fun isAccountNonExpired(): Boolean = true
override fun isAccountNonLocked(): Boolean = true
Expand Down

0 comments on commit 3c1c44a

Please sign in to comment.