Praneeth
Praneeth

Reputation: 2547

Asp.net Core 2.0 Custom Cookie based authentication

I have upgraded from asp.net core 1.0 to asp.net core 2.0 I need url based authentication which create a authorized cookie. There is no Login page. If url contains certain token I need to authenticate the request if not redirect them to error page. I am stuck in redirect loop. what's wrong in my code

ConfigureServices method

 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = new PathString("/Error/");
                    options.AccessDeniedPath = new PathString("/Error/");
                    options.SlidingExpiration = true;
                    options.ExpireTimeSpan = TimeSpan.FromMinutes(20);

                });

Configure Method

app.UseAuthentication();
app.ValidateRequest(Configuration);

In validaterequest middleware

public Task Invoke(HttpContext context)
        {
                context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                   principal,
                   new AuthenticationProperties
                   {
                       ExpiresUtc = DateTime.UtcNow.AddSeconds(expiration),
                       IsPersistent = true,
                       AllowRefresh = true,
                       IssuedUtc = DateTime.UtcNow,
                   });
return _next.Invoke(context);
}


[MiddlewareFilter(typeof(validaterequestPipeline))]
    public class HomeController : Controller
    {
      [Authorize]
        [HttpGet]
        public IActionResult Index()
        {
        }
   }

Upvotes: 1

Views: 2610

Answers (1)

Praneeth
Praneeth

Reputation: 2547

Login was working properly on http/localhost but once it is on https/subdomain.domain.com it didn't work. Change was to do this

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.LoginPath = new PathString("/account/signin");
    options.SlidingExpiration = true;
    options.ExpireTimeSpan = TimeSpan.FromMinutes(20);
    options.Cookie.SameSite = SameSiteMode.None;
});

options.Cookie.SameSite = SameSiteMode.None;

Upvotes: 2

Related Questions