You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Identity Server 3:登录后跳转带令牌前展示数据采集界面的实现

Got it, let's break down how to add a mandatory user info collection step right after login in Identity Server 3—mirroring the consent screen experience—and enforce this for all your clients (Android, Angular, ASP.NET, you name it). Here's a practical, step-by-step approach:

Step 1: Build a Custom User Info Collection UI & Controller

First, you'll need a screen to collect the required data (like phone number, address, etc.)—think of it as a second "step" after login.

Create a controller that inherits from Identity Server's base controller to tap into its context, plus a corresponding view with form fields for your required info:

public class UserInfoCollectionController : IdentityServerController
{
    // Show the collection form
    [HttpGet]
    public ActionResult Index(string returnUrl)
    {
        // Save the original return URL to resume the auth flow later
        TempData["OriginalReturnUrl"] = returnUrl;

        // Skip if user already has the required info
        var currentUser = User as ClaimsPrincipal;
        if (currentUser.HasClaim(c => c.Type == "phone_number"))
        {
            return Redirect(returnUrl);
        }

        return View(new UserInfoCollectionViewModel());
    }

    // Process the submitted form
    [HttpPost]
    public async Task<ActionResult> Index(UserInfoCollectionViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // Save the collected data to your user store (adjust to match your setup)
        var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var user = await userManager.FindByIdAsync(User.GetSubjectId());
        
        user.PhoneNumber = model.PhoneNumber;
        user.StreetAddress = model.StreetAddress;
        await userManager.UpdateAsync(user);

        // Update the current user's claims to include the new data
        var updatedIdentity = await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(updatedIdentity);

        // Jump back to the original auth flow
        var returnUrl = TempData["OriginalReturnUrl"] as string;
        return Redirect(returnUrl);
    }
}

Your view (Index.cshtml) will be a simple form bound to UserInfoCollectionViewModel, with validation for required fields—nothing fancy, just like the consent screen's clean layout.

Step 2: Hook Into Identity Server's Login Success Event

Identity Server 3 lets you intercept the login pipeline via events. We'll use the LoginSuccess event to check if the user needs to provide additional info, and redirect them to our collection screen if they do:

var identityServerOptions = new IdentityServerOptions
{
    // Your existing config (issuer, signing keys, stores, etc.)
    Events = new EventsOptions
    {
        LoginSuccess = async context =>
        {
            // Check if the user is missing mandatory claims
            var user = context.Result.Principal;
            if (!user.HasClaim(c => c.Type == "phone_number"))
            {
                // Redirect to our collection page, passing the original return URL
                context.RedirectUri = Url.Action("Index", "UserInfoCollection", new { returnUrl = context.RedirectUri });
                context.Handled(); // Tell Identity Server we're taking over this step
            }
            return Task.CompletedTask;
        }
    }
};

This ensures every user—regardless of which client they're coming from—hits the collection screen if they haven't provided the required data yet.

Step 3: Ensure Flow Consistency Across All Clients

Since we're tapping into Identity Server's core login pipeline, this works for every client type:

  • For server-side clients (like ASP.NET MVC), the return URL will point to Identity Server's authorization endpoint, which will continue issuing the token after info collection.
  • For SPA/mobile clients (Angular, Android), the flow will resume seamlessly, with the token being sent to the client's callback URL as usual.

Just make sure your UserInfoCollectionViewModel includes all the fields you need, and add server-side validation to ensure data quality.

Step 4: Handle Edge Cases
  • Session persistence: If you're worried about TempData expiring (for users who take time to fill out the form), you can store the original return URL in a database tied to the user's session ID instead.
  • Retry logic: If the user submits invalid data, the view should show validation errors just like any standard form.
  • Existing users: For users who already logged in before you added this step, the LoginSuccess check will catch them on their next login and prompt for the missing info.

That's it! This setup integrates seamlessly into Identity Server's login flow, enforces the info collection for all clients, and mirrors the familiar consent screen pattern users already know.

内容的提问来源于stack exchange,提问作者Kiran B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:36:32