Monday, February 7, 2022

ASP.NET Authorization setup

 Plugin:

Microsoft.Owin

Microsoft.Owin.Host.SystemWeb

Microsoft.Owin.Security.Cookies


Startup.Auth:

Create a Startup.Auth class into the App_Start folder: Startup.Auth.cs

using System;

using Microsoft.Owin;

using Microsoft.Owin.Security.Cookies;

using Owin;


namespace [Project_name]

{

    public static class MyAuthentication

    {

        public const String ApplicationCookie = "xyz";

    }


    public partial class Startup

    {

        public void ConfigureAuth(IAppBuilder app)

        {

            // need to add UserManager into owin, because this is used in cookie invalidation

            app.UseCookieAuthentication(new CookieAuthenticationOptions

            {

                AuthenticationType = MyAuthentication.ApplicationCookie,

                LoginPath = new PathString("/Home/Login"),

                Provider = new CookieAuthenticationProvider(),

                CookieName = "abc",

                CookieHttpOnly = true,

                ExpireTimeSpan = TimeSpan.FromHours(12), // adjust to your needs

            });

        }

    }

}

OWIN.Startup:

Create an OWIN.Startup class into the root : Startup.cs


using Microsoft.Owin;

using Owin;


[assembly: OwinStartupAttribute(typeof([Project_name].Startup))]

namespace [Project_name]

{

    public partial class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            ConfigureAuth(app);

        }

    }

}



Now add this code to the Global.asax Page

protected void Application_BeginRequest()

        {

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));

            Response.Cache.SetNoStore();

        }




No comments:

Post a Comment