Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

Your company is moving user accounts from a local database to an external identity provider over six months. During the migration some users exist only in the old database. How would you design authentication in the Spring application?

During the migration the application runs two login paths side by side: OIDC login against the new identity provider for users who have moved, and the existing UserDetailsService with form login for users who have not. An identifier-first login page looks up a migration flag and sends each user to the right path, local logins quietly migrate the account into the provider, and both paths map to the same internal roles. We track how many users are left and close the old path on a fixed date.

Why this question is asked

Moving users to an external identity provider is rarely a single weekend cutover. Accounts move in waves, some users log in once a quarter, and the business will not accept locking people out. Interviewers ask this question to see whether we can keep authentication correct while two sources of truth exist, and whether we know which Spring Security pieces make that possible. In this answer, we will recap the two login mechanisms involved, see how to route each user to the right one, migrate accounts as people log in, keep roles consistent across both paths, and finally plan how the old path ends.

1A Quick Recap of the Two Login Paths

The old system authenticates locally. A user submits a username and password in a form, Spring Security's DaoAuthenticationProvider asks our UserDetailsService to load the user from the database, and the PasswordEncoder checks the password against the stored hash. Everything happens inside our application.

The new system uses OpenID Connect (OIDC), a login protocol built on OAuth 2.0. Our application does not see the password at all. It redirects the browser to the identity provider, the provider authenticates the user, and the browser comes back with an authorization code that Spring exchanges for an ID token, a signed document that says who the user is. In Spring Security this is oauth2Login().

Spring Security is happy to run both in the same filter chain. Each mechanism has its own filter and its own URL, so a form post to /login goes to the local path and a redirect to /oauth2/authorization/idp goes to the new one.

Java
@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(a -> a
.requestMatchers("/login", "/login/start").permitAll()
.anyRequest().authenticated())
.formLogin(f -> f.loginPage("/login")) // local path: UserDetailsService + PasswordEncoder
.oauth2Login(o -> o.loginPage("/login")); // new path: OIDC against the identity provider
return http.build();
}

Notice that both mechanisms share one login page. That page is where we decide which path a given user takes.

2Routing Each User With an Identifier-First Page

If we show two buttons, users will pick the wrong one and call support. A better design asks for the email address first, before any password. The server then looks up the user's migration state and redirects. This pattern is called identifier-first login.

We keep a small table, or a column on the old user table, with values such as LOCAL, MIGRATED and DISABLED. For a migrated user we redirect to the provider and pass the email as a login hint so the user does not type it twice. For a local user we show the password form.

Java
@PostMapping("/login/start")
String start(@RequestParam String email, HttpServletResponse res) {
MigrationState state = migration.stateOf(email); // LOCAL, MIGRATED or UNKNOWN
return switch (state) {
case MIGRATED, UNKNOWN -> "redirect:/oauth2/authorization/idp?login_hint=" + urlEncode(email);
case LOCAL -> "redirect:/login?email=" + urlEncode(email); // shows the password form
};
}
Step throughHow a login is routed during the migration
  1. User enters emailidentifier-first page
  2. Migration flag says MIGRATED?
    YesRedirect to the identity providerNoShow the local password form
  3. Local password correct?
    YesCreate the account in the provider, mark MIGRATEDNoShow the normal error
  4. Map roles from the internal tablesame authorities on both paths

4 steps in order. Play them, or step through them one at a time.

There is a catch: the login_hint parameter on our own URL is not passed to the provider automatically. We add it with an authorization request customizer on DefaultOAuth2AuthorizationRequestResolver, which copies it into the request sent to the provider. Notice also that unknown users go to the provider, so new sign-ups are created only there and the old database stops growing. To avoid revealing which emails exist, the response time and the page should look the same in every branch.

3Migrating Accounts as Users Log In

The quietest migration happens on login. When a local user types the correct password, we know the plain password for a moment, so we can create the account in the identity provider through its admin API and flip the flag. The next login goes through OIDC.

The place to do this matters. Spring Security erases the credentials from the Authentication after a successful login, so a normal success handler is too late to see the password. We wrap the DaoAuthenticationProvider in a small provider of our own that migrates after the delegate succeeds.

Java
class MigratingAuthenticationProvider implements AuthenticationProvider {
private final DaoAuthenticationProvider local;
private final IdpAdminClient idp;
private final MigrationRepository migration;
public Authentication authenticate(Authentication request) {
Authentication result = local.authenticate(request); // throws BadCredentialsException if wrong
String raw = (String) request.getCredentials(); // still available here
try {
idp.createUser(result.getName(), raw); // or import the stored hash
migration.markMigrated(result.getName());
} catch (IdpException e) {
log.warn("migration failed for one user, will retry next login"); // login still succeeds
}
return result;
}
public boolean supports(Class<?> type) { return local.supports(type); }
}

Notice that a failure to migrate never blocks the login. The user is authenticated locally, and we simply try again next time. If the provider can import password hashes in our format (many accept bcrypt hashes, but check your provider), we can go further and bulk-import every account up front, so even users who never log in during the six months arrive with a working password.

4Keeping Roles the Same on Both Paths

Authorization must not depend on how the user logged in. Locally, roles come from our UserDetailsService. Through OIDC, they may come from a groups claim in the token, or from nowhere at all if the provider only knows identities.

The simplest rule is to keep one internal role table keyed by the user's email or a stable user id, and have both paths read it. For OIDC we plug in a GrantedAuthoritiesMapper or a custom OidcUserService that looks up the same table, so ROLE_ADMIN means the same thing whichever filter authenticated the request.

Java
@Bean
GrantedAuthoritiesMapper oidcRoles(RoleRepository roles) {
return authorities -> authorities.stream()
.filter(OidcUserAuthority.class::isInstance)
.map(a -> ((OidcUserAuthority) a).getIdToken().getEmail())
.flatMap(email -> roles.rolesFor(email).stream()) // same table the UserDetailsService uses
.map(r -> new SimpleGrantedAuthority("ROLE_" + r))
.collect(Collectors.toSet());
}

We should write one test per path that logs in the same user and asserts the same authorities. That test is what catches a missed mapping before a migrated administrator loses access.

5Ending the Old Path on Purpose

A migration without an end date never ends. We add a metric for the number of LOCAL accounts and how many local logins happen per day, and we watch it fall. After two or three months the curve flattens: the remaining users are the inactive ones.

For those, we set a deadline. After it, the local form is removed, any remaining accounts are either bulk-imported into the provider with a forced password reset on first login or disabled, and the UserDetailsService and password hashes are deleted. Removing the old code and data is the real finish line, because a forgotten password table is a liability that nobody watches.

6Follow-up questions

Why not simply bulk-import everyone on day one?

If the provider supports importing our hash format, that is often the best plan, and the on-login step becomes a safety net. Many providers do not accept every format, though, and some data such as old roles or unverified emails needs cleaning first. Migrating on login also spreads the risk: problems show up for a few users at a time instead of for everyone at once.

What happens to sessions that started on the old path?

They stay valid until they expire, because a session only holds the authenticated principal. Since both paths produce the same authorities, the rest of the application does not care. We just make sure logout works for both, including RP-initiated logout at the provider for OIDC users.

7Conclusion

In this answer, we saw how to run local form login and OIDC login in the same Spring Security configuration, route each user with an identifier-first page and a migration flag, migrate accounts on successful local login without blocking the user, and map both paths to one internal role table. We closed the old path with a measured decline and a firm deadline, followed by deleting the old credentials.

What to say in the interviewAbout 90 seconds aloud

Open with

I would run both login paths in one filter chain: formLogin backed by the existing UserDetailsService for users still in the old database, and oauth2Login against the new identity provider for users who have moved.

Then, if they want more

To stop users from choosing the wrong path, I would use an identifier-first page: the user enters their email, I look up a migration flag, and I either show the password form or redirect to the provider with a login hint. Unknown users go to the provider, so new accounts are only created there.

For the migration itself I would migrate on login. I wrap the DaoAuthenticationProvider, and after a successful local login, while I still have the raw password, I create the account in the provider through its admin API and mark the user as migrated.

If the provider can import bcrypt hashes, I would bulk-import everyone up front and keep the on-login step as a fallback. Authorization must not depend on the login path, so both the UserDetailsService and a GrantedAuthoritiesMapper for OIDC read the same internal role table, and I test that the same user gets the same authorities both ways.

Finally I would track the number of local accounts and local logins, set a deadline, force a reset or disable the remaining inactive accounts, and then delete the old password data and code.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring Security reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Your company is moving user accounts from a local database to an external identity...": https://scrivio-interview-library.netlify.app/spring-boot/authentication/f56cdbeee4/