Protecting endpoints using Session cookie ASP.NET Core

Viewed 204

Is there a native ASP.NET Core method for securing endpoints via a Session Cookie? I have successfully implemented a Session using a Cosmos backing store by following the article on MSFT but have yet to figure out how to translate that into securing my endpoints.

Cookie authentication seems like the way to go but I cannot figure out how to quite get it right.

I feel like by using:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

I am instead creating another cookie instead of reusing the one given to me by the Session middleware.

Ultimately, I want to be able to only allow for specific endpoints to be called if the user has a session and it is a valid one. Thanks!

1 Answers

I did this on recent project by implementing my own session storage in Cosmos DB via ITicketStore (not with AddSession). You configure the CookieAuthenticationOptions to persist authentication tickets through your custom store. Here's the gist, which allows using either cookies or JWT depending on whether request comes from browser or API client.

The service configuration bits:

// Authenticate using shared cookie for browser clients, and JWT tokens for API clients
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, cookieOptions)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtOptions);

// Authorize with both cookies and JWT bearer tokens
// Requires all controllers have attribute [Authorize(AuthenticationSchemes = "Bearer, Cookies")]
services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder(
        CookieAuthenticationDefaults.AuthenticationScheme,
        JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser().Build();
});

// Persistent ticket/cookie store to provide durable user sessions
services.AddSingleton<ITicketStore, MyCustomTicketStore>();
services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
    .Configure<ITicketStore>((options, store) => options.SessionStore = store);

Discussed in context a bit in this presentation.

Related