ASP.NET 5 / MVC 6 Redirecting During Intermediate Event Authentication

What I want to do is create a database record and redirect the user to a special page when I first enter the site - regardless of the original URL. Subsequent entries should update the last completed field in the database.

I am using an external authentication source with cookie authentication. It seems intuitive to do these things during an event OnSignedInfor cookie authentication. Parts of the database of this process work fine. The problem is redirected to a special landing page during their first login.

Here's how cookie authentication is configured:

app.UseCookieAuthentication(options =>
{   
    options.AuthenticationScheme = "Cookies";
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;

    options.LoginPath = "/login";
    options.AccessDeniedPath = "/access-denied";

    options.Events = new CookieAuthenticationEvents
    {
        OnSignedIn = context =>
        {
            var userRecord = userService.GetUser(context.Principal.Identity.Name);

            if (userRecord == null)
            {
                userService.CreateUser(context.Principal.Identity.Name);

                // Does set a cookie successfully.
                context.Response.Cookies.Append("FirstTimeUser", "true");   
                // Does not redirect but continues on to the originally requested URL.
                context.Response.Redirect("/special-first-timer-page");     
            }
            else
            {
                userService.RecordLogin(userRecord);
            }

            return Task.FromResult(0);
        }
    };
});         

, , cookie OnSignedIn.

app.Use(async (context, next) =>
{
    if (context.Request.Cookies.ContainsKey("FirstTimeUser"))
    {
        context.Response.Cookies.Delete("FirstTimeUser");
        context.Response.Redirect("/special-first-timer-page");
    }

    await next();
});

app.UseCookieAuthentication(options =>
{
    ...

    options.Events = new CookieAuthenticationEvents
    {
        OnSignedIn = context =>
        {
            var userRecord = userService.GetUser(context.Principal.Identity.Name);

            if (userRecord == null)
            {
                userService.CreateUser(context.Principal.Identity.Name);
                context.Response.Cookies.Append("FirstTimeUser", "true");
            }
            else
            {
                userService.RecordLogin(userRecord);
            }

            return Task.FromResult(0);
        }
    };
});

, . ? , ?

+4

Source: https://habr.com/ru/post/1620625/


All Articles