Modeling 1:N social account linking and separate admin OAuth2
Model 1:N social accounts with JPA, prevent account takeover via one-time link tickets, and isolate stateless API OAuth2 from session-based admin login.
Storing
oauth_providerandoauth_iddirectly on theUsertable works until you need a second social provider. This post walks through splittingUserandSocialAccountinto a 1:N model, enforcing safe account linking with one-time tickets, and separating stateless SPA OAuth2 from session-based admin login in Spring Security.
Requirements: linking and unlinking multiple providers safely
Early in a project, it’s tempting to add oauth_provider and oauth_id columns straight onto the users table for a single provider like Kakao or Google. The shortcut breaks down as soon as you support multiple Identity Providers (IdPs). Adding kakao_id, google_id, and naver_id columns forces a schema migration every time a new provider arrives and scatters authentication logic across the User entity.
In production, multi-provider social login needs four firm rules:
- 1:N account linking: One user can link Kakao, Google, and Naver to the same account and sign in with any of them.
- No cross-user collision: A social identity already linked to User A can’t be linked to User B.
- Protect the last login method: If a social-only user has no local password, block them from unlinking their final social provider so they don’t lock themselves out permanently.
- No silent email-based merging: Never auto-link a social login to an existing account just because the email addresses match. Without verifying ownership of both sides, an attacker using an unverified IdP email can take over an existing user’s account.
Domain model: separating User and SocialAccount (1:N)
To enforce those rules cleanly, I split SocialAccount into its own entity under the User aggregate root.
erDiagram
users ||--o{ social_accounts : "1 : N"
users {
uuid id PK
varchar email UK "Nullable"
varchar password "Nullable (social-only)"
varchar nickname
timestamp created_at
}
social_accounts {
uuid id PK
uuid user_id FK
varchar provider "KAKAO, GOOGLE, NAVER"
varchar provider_id "Provider-scoped unique ID"
varchar provider_email
timestamp created_at
}
Composite unique constraints
Application-level checks alone aren’t enough under concurrent requests, so social_accounts enforces two composite unique constraints at the database level:
uk_social_account_provider_id (provider, provider_id): One external social identity can belong to at most one user in the system.uk_social_account_user_provider (user_id, provider): One user can’t link two accounts from the same provider (for example, two separate Google accounts).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/main/kotlin/com/example/server/user/domain/SocialAccount.kt
package com.example.server.user.domain
import com.example.server.common.BaseEntity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.EnumType
import jakarta.persistence.Enumerated
import jakarta.persistence.FetchType
import jakarta.persistence.GeneratedValue
import jakarta.persistence.Id
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
import jakarta.persistence.Table
import jakarta.persistence.UniqueConstraint
import java.util.UUID
import org.hibernate.annotations.UuidGenerator
@Entity
@Table(
name = "social_accounts",
uniqueConstraints = [
UniqueConstraint(name = "uk_social_account_provider_id", columnNames = ["provider", "provider_id"]),
UniqueConstraint(name = "uk_social_account_user_provider", columnNames = ["user_id", "provider"]),
]
)
class SocialAccount(
@Id
@GeneratedValue
@UuidGenerator(style = UuidGenerator.Style.VERSION_7)
@Column(columnDefinition = "UUID", updatable = false)
var id: UUID? = null,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id", nullable = false)
val user: User,
@Enumerated(EnumType.STRING)
@Column(nullable = false)
val provider: Provider,
@Column(name = "provider_id", nullable = false)
val providerId: String,
@Column(nullable = true)
var providerEmail: String? = null,
) : BaseEntity()
Encapsulating link and unlink invariants on User
Linking, unlinking, and protecting the last login method all live directly on User rather than leaking into service classes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// src/main/kotlin/com/example/server/user/domain/User.kt
package com.example.server.user.domain
import com.example.server.common.BaseEntity
import com.example.server.common.BusinessException
import jakarta.persistence.CascadeType
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.Id
import jakarta.persistence.OneToMany
import jakarta.persistence.Table
import java.time.Instant
import java.util.UUID
import org.hibernate.annotations.UuidGenerator
@Entity
@Table(name = "users")
class User(
@Id
@GeneratedValue
@UuidGenerator(style = UuidGenerator.Style.VERSION_7)
@Column(columnDefinition = "UUID", updatable = false)
var id: UUID? = null,
@Column(unique = true, nullable = true)
var email: String? = null,
@Column(nullable = true)
var password: String? = null,
@Column(nullable = false)
var nickname: String,
@OneToMany(mappedBy = "user", cascade = [CascadeType.ALL], orphanRemoval = true)
val socialAccounts: MutableSet<SocialAccount> = mutableSetOf(),
) : BaseEntity() {
fun linkSocialAccount(provider: Provider, providerId: String, providerEmail: String?): SocialAccount {
if (socialAccounts.any { it.provider == provider }) {
throw BusinessException(SocialErrorCode.PROVIDER_ALREADY_LINKED)
}
val account = SocialAccount(
user = this,
provider = provider,
providerId = providerId,
providerEmail = providerEmail,
)
socialAccounts.add(account)
return account
}
fun unlinkSocialAccount(provider: Provider) {
val account = socialAccounts.find { it.provider == provider }
?: throw BusinessException(SocialErrorCode.SOCIAL_ACCOUNT_NOT_FOUND)
// Block unlinking the sole login method for social-only users without a password
if (password == null && socialAccounts.size == 1) {
throw BusinessException(SocialErrorCode.LAST_LOGIN_METHOD)
}
socialAccounts.remove(account)
}
override fun onDelete(at: Instant) {
socialAccounts.clear()
email = email?.let { deletedEmail(it, at) }
}
}
Explicit account-linking workflow with one-time tickets
Social OAuth2 flows fall into two distinct modes: Sign In (unauthenticated) and Link (an already-authenticated user connecting an extra provider).
sequenceDiagram
autonumber
actor User as User (Browser)
participant Client as Frontend (SPA)
participant Server as Backend Server
participant IdP as Social Provider (Kakao/Google)
Note over User,Server: 1. Initiate account linking
Client->>Server: POST /api/v1/users/me/social-accounts/{provider}/link
Server-->>Client: Return OAuth2 authorize URL with 1-time link_ticket
Client->>IdP: Redirect to IdP (store state cookie + link_ticket attribute)
User->>IdP: Sign in and grant consent
IdP-->>Server: GET /api/v1/auth/social/{provider}/callback?code=...
Server->>IdP: Exchange authorization code & fetch user profile
Server->>Server: Consume link_ticket & call User.linkSocialAccount()
Server-->>Client: 302 Redirect: {frontend}/oauth/callback?linked={provider}
Client->>User: Refresh linked provider badges on profile page
When an authenticated user starts linking a provider, the backend mints a 60-second, single-use link_ticket mapped to their userId in Redis. LinkTicketAuthorizationRequestResolver captures that parameter and stores it inside the OAuth2AuthorizationRequest attributes. When the IdP redirects back, the callback handler consumes the ticket once, recovers the verified userId, and links the social profile—no session state required.
Isolating user API OAuth2 from admin web OAuth2
In a single Spring Boot application serving both a public SPA and an internal back-office, user login and admin login have opposite security requirements:
| Aspect | Public API (SPA) | Admin Console (Thymeleaf) |
|---|---|---|
| Session policy | STATELESS (JWT access/refresh tokens) | IF_REQUIRED (Redis-backed HttpSession) |
| CSRF & fixation | CSRF disabled on stateless token endpoints | CSRF enabled + changeSessionId() fixation protection |
| Auto sign-up | Allowed (allowSignUp = true) | Blocked (allowSignUp = false; pre-linked admins only) |
| OAuth2 state store | Signed HttpOnly cookie (SameSite=Lax) | Default HttpSession repository |
Splitting SecurityFilterChain beans
As I covered in my guide on multiple Spring Security filter chains, separating these entry points into ordered SecurityFilterChain beans keeps stateless and stateful rules from leaking into each other.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// src/main/kotlin/com/example/server/security/api/ApiSecurityConfig.kt
@Configuration
class ApiSecurityConfig(
private val apiSecurityHandlers: ApiSecurityHandlers,
@Value("\${app.frontend.url}") private val frontendUrl: String,
) {
@Bean
@Order(1)
fun apiSocialLoginFilterChain(
http: HttpSecurity,
clientRegistrationRepository: ClientRegistrationRepository,
authorizationRequestRepository: CookieOAuth2AuthorizationRequestRepository,
socialOAuth2UserService: SocialOAuth2UserService,
apiSocialLoginHandler: ApiSocialLoginHandler,
): SecurityFilterChain {
http
.securityMatcher(
OrRequestMatcher(
PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.GET, "/api/v1/auth/social/{provider}"),
PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.GET, "/api/v1/auth/social/{provider}/callback"),
)
)
.csrf { it.disable() }
.sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) }
.securityContext { it.securityContextRepository(NullSecurityContextRepository()) }
.oauth2Login { oauth2 ->
oauth2.authorizationEndpoint {
it.baseUri("/api/v1/auth/social")
it.authorizationRequestRepository(authorizationRequestRepository)
it.authorizationRequestResolver(
ApiSocialLoginHandler.LinkTicketAuthorizationRequestResolver(
clientRegistrationRepository,
"/api/v1/auth/social",
)
)
}
oauth2.redirectionEndpoint { it.baseUri("/api/v1/auth/social/*/callback") }
oauth2.userInfoEndpoint { it.userService(socialOAuth2UserService) }
oauth2.successHandler(apiSocialLoginHandler)
oauth2.failureHandler(apiSocialLoginHandler)
}
return http.build()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/main/kotlin/com/example/server/security/admin/AdminWebSecurityConfig.kt
@Configuration
class AdminWebSecurityConfig {
@Bean
@Order(3)
fun adminWebFilterChain(
http: HttpSecurity,
clientRegistrationRepository: ClientRegistrationRepository,
socialOAuth2UserService: SocialOAuth2UserService,
adminSocialLoginHandler: AdminSocialLoginHandler,
): SecurityFilterChain {
http
.securityMatcher("/admin/**")
.authorizeHttpRequests {
it.requestMatchers("/admin/login", "/admin/403").permitAll()
it.anyRequest().hasRole(UserRole.ADMIN.name)
}
.formLogin {
it.loginPage("/admin/login")
it.defaultSuccessUrl("/admin/dashboard")
}
.oauth2Login { oauth2 ->
oauth2.loginPage("/admin/login")
oauth2.authorizationEndpoint {
it.baseUri("/admin/oauth2/authorization")
it.authorizationRequestResolver(
AdminSocialLoginHandler.AdminAuthorizationRequestResolver(
clientRegistrationRepository,
"/admin/oauth2/authorization",
"/admin/login/oauth2/code",
)
)
}
oauth2.redirectionEndpoint { it.baseUri("/admin/login/oauth2/code/*") }
oauth2.userInfoEndpoint { it.userService(socialOAuth2UserService) }
oauth2.successHandler(adminSocialLoginHandler)
oauth2.failureHandler(adminSocialLoginHandler)
}
.sessionManagement {
it.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
it.sessionFixation { fixation -> fixation.changeSessionId() }
}
return http.build()
}
}
Cookie-based OAuth2 state and one-time code exchange
Because the API chain uses SessionCreationPolicy.STATELESS, Spring Security’s default HttpSessionOAuth2AuthorizationRequestRepository won’t work. Instead, CookieOAuth2AuthorizationRequestRepository serializes the authorization request (state, code_verifier, and optional link_ticket) into a short-lived, HMAC-signed HttpOnly cookie (SameSite=Lax), preserving statelessness while still blocking login CSRF.
On callback success, ApiSocialLoginHandler never puts JWTs in the redirect query string—tokens in URLs leak through browser history, proxy logs, and Referer headers. It redirects with a short-lived one-time code (code), which the SPA exchanges via POST /api/v1/auth/social/token for the actual JWT pair.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// src/main/kotlin/com/example/server/auth/social/ApiSocialLoginHandler.kt
@Component
class ApiSocialLoginHandler(
private val socialAccountService: SocialAccountService,
private val oneTimeCodeStore: OneTimeCodeStore,
@Value("\${app.frontend.url}") private val frontendUrl: String,
@Value("\${app.frontend.callback-path}") private val callbackPath: String,
) : AuthenticationSuccessHandler {
override fun onAuthenticationSuccess(
request: HttpServletRequest,
response: HttpServletResponse,
authentication: Authentication,
) {
val principal = authentication.principal as SocialPrincipal
val authorizationRequest = request.getAttribute(
CookieOAuth2AuthorizationRequestRepository.REMOVED_REQUEST_ATTRIBUTE
) as? OAuth2AuthorizationRequest
val linkTicket = authorizationRequest?.getAttribute<String>(LINK_TICKET_PARAMETER)
val params = try {
if (linkTicket != null) {
val userId = oneTimeCodeStore.consume(OneTimeCodeStore.Purpose.SOCIAL_LINK, linkTicket)
?: throw BusinessException(SocialErrorCode.INVALID_LINK_TICKET)
socialAccountService.link(userId, principal)
mapOf("linked" to principal.provider.registrationId)
} else {
val user = socialAccountService.login(principal, allowSignUp = true)
mapOf("code" to oneTimeCodeStore.issue(OneTimeCodeStore.Purpose.SOCIAL_LOGIN, user.id!!))
}
} catch (e: BusinessException) {
mapOf("error" to (e.errorCode as Enum<*>).name)
}
val builder = UriComponentsBuilder.fromUriString("$frontendUrl$callbackPath")
params.forEach { (key, value) -> builder.queryParam(key, value) }
DefaultRedirectStrategy().sendRedirect(request, response, builder.encode().build().toUriString())
}
companion object {
const val LINK_TICKET_PARAMETER = "link_ticket"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// src/main/kotlin/com/example/server/auth/social/AdminSocialLoginHandler.kt
@Component
class AdminSocialLoginHandler(
private val socialAccountService: SocialAccountService,
private val userRepository: UserRepository,
) : AuthenticationSuccessHandler {
private val securityContextRepository: SecurityContextRepository = HttpSessionSecurityContextRepository()
override fun onAuthenticationSuccess(
request: HttpServletRequest,
response: HttpServletResponse,
authentication: Authentication,
) {
val principal = authentication.principal as SocialPrincipal
try {
// Admins must already exist and be pre-linked; reject unknown social accounts
val user = socialAccountService.login(principal, allowSignUp = false)
val authUser = AuthUser.from(user).also { it.eraseCredentials() }
val context = SecurityContextHolder.createEmptyContext()
context.authentication = UsernamePasswordAuthenticationToken.authenticated(authUser, null, authUser.authorities)
SecurityContextHolder.setContext(context)
securityContextRepository.saveContext(context, request, response)
DefaultRedirectStrategy().sendRedirect(request, response, "/admin/dashboard")
} catch (e: BusinessException) {
val context = SecurityContextHolder.createEmptyContext()
SecurityContextHolder.setContext(context)
securityContextRepository.saveContext(context, request, response)
DefaultRedirectStrategy().sendRedirect(request, response, "/admin/login?error=${(e.errorCode as Enum<*>).name}")
}
}
}
Soft-delete pitfalls with unique constraints
Soft-deleting a user creates a classic trap when unique constraints exist on social_accounts and users.email (see my earlier note on JPA soft deletes and unique index conflicts).
If you leave a withdrawn user’s
SocialAccountrows in the database, that person won’t be able to sign up again with the same Kakao or Google account—PostgreSQL will reject the insert onuk_social_account_provider_id.
In User.onDelete(at) above, I handle both columns explicitly:
- Hard-delete
SocialAccountrows: CallingsocialAccounts.clear()withorphanRemoval = trueremoves the linked provider rows immediately, freeing(provider, provider_id)for future re-registration. - Mangle the soft-deleted email: Appending a timestamp suffix (
email@deleted_yyyyMMdd-HHmmss) frees theusers.emailunique constraint while preserving the soft-deleted audit record.
Verification
Linked providers on the profile screen
On the user profile page, Kakao and Google show up as linked badges while Naver remains available to connect:
Figure 1. Profile UI reflecting 1:N linked social accounts (Kakao and Google linked, Naver unlinked).
One-time code exchange for JWTs
After the OAuth2 redirect completes, the frontend exchanges the single-use slc_... code at POST /api/v1/auth/social/token to receive the access and refresh tokens:
Figure 2. Exchanging a single-use social login code for an access/refresh token pair.
User vs. admin OAuth2 flow comparison
The diagram below summarizes how the stateless SPA flow and the session-backed admin flow stay isolated inside the same Spring Boot service:
Figure 3. Side-by-side comparison of stateless SPA OAuth2 and session-based admin OAuth2 entry points.
Summary checklist
- Model social accounts as 1:N: Separate
SocialAccountfromUserwith composite unique constraints on(provider, provider_id)and(user_id, provider). - Require explicit linking: Use a short-lived
link_ticketinstead of merging accounts by email address, and block unlinking the last login method whenpassword == null. - Isolate filter chains: Keep stateless JWT OAuth2 (cookie state + one-time code exchange +
allowSignUp = true) completely separate from session-backed admin OAuth2 (allowSignUp = false). - Clear social rows on soft delete: Hard-delete
SocialAccountchildren on withdrawal so users can re-register later without hitting unique-key errors.