Home > Blockchain >  C# How to share authentication/authorization cookie between projects?
C# How to share authentication/authorization cookie between projects?

Time:03-26

It's a rather question related with conceptual approach.

So I have two projects - in one the Authentication is already implemented and working ok. It's a .net core SPA with OpenID Cookie (without without ASP.NET Core Identity).

The second project is the REST API that I want to use that cookie to Authorize some of the endpoints so basically SSO.

The biggest challenge to me is I don't know how I should modify second project to "accept" the cookie from first one - I need at least some starting point.

This one is not helping at all: enter image description here

CodePudding user response:

The documentation you referenced actually has everything you need. But it requires some basic knowledge to understand that. To use the cookie set by one app in another you need to ensure two things:

  1. The cookie should be sent to both app
    1.1. If apps hosted on the same domain but on different paths, you need to set cookie Path to the common denominator. For example, here the common denominator is /:
    https://my-domain.com/app1
    https://my-domain.com/app2
    Here is /api (but / is also valid)
    https://my-domain.com/api/app1
    https://my-domain.com/api/app2
    1.2 If apps hosted on different domains, they must be subdomains of some common domain. Set cookie domain to the common domain value to share it between subdomains.
    For example, here the common domain is .company.com:
    https://sub-domain1.company.com
    https://sub-domain2.company.com
    This is also example of common domain .company.com
    https://company.com
    https://sub-domain2.company.com
    But these 2 domains can't share cookies because they don't have common domain:
    https://sub-domain1.company1.com
    https://sub-domain2.company2.com
    1.3 You can also mix domain and path configuration if your apps hosted on different domains with common sub-domain and different path. For example, here the domain should be .company.com and path /:
    https://sub-domain1.company.com/api/app1
    https://sub-domain2.company.com/app2

  2. Both app can decrypt the cookie and understand its content.
    2.1 If apps hosted on the same machine you can use file storage to persist data protection keys:

services.AddDataProtection()
    .PersistKeysToFileSystem("{PATH TO COMMON KEY RING FOLDER}")

2.2 If the apps hosted on different machines you need to use another type of storage so that both app will be able to access it and read protection keys. For example, you can use Amazon KMS service with Amazon.AspNetCore.DataProtection.SSM nuget:

services.AddDataProtection()
    .PersistKeysToAWSSystemsManager("/MyApplication/DataProtection");
  • Related