Search code examples
asp.net-identityidentityserver4

Accessing a protected .net API with a token from IdentityServer4


I have working prototype Visual Studio Solution using IdentityServer4 which has:

  • IdentityServer (asp.net core mvc)
  • API project (asp.net core mvc)
  • Web Client 1 (MVC/Angular) (Username/password protected admin portal) talking to API
  • Web Client 2 (MVC) (Public facing website, no login)

I have the login working and basic test of Web Client 1 working talking to API.

My question is best described using an example: Suppose I have a method in my API protected with the [Authorize] attribute for GetCourses (protected with authorize so its not accessible by anybody if they know the URL). This currently work because my test is logging in with a user on web client 1 (which would be used to edit courses eventually).

But on my Public facing website I want to be able to call GetCourses with ClientCredentials in IdentityServer so I can display a list of courses on the website. I expect I'm going about this the wrong way so if anyone can provide any pointers it would be much appreciated.

Thanks Richard


Solution

  • Assuming you use cookie authentication for Web Client 1:

      // for Web Client 1  Scheme = Cookies
      app.UseCookieAuthentication();
    
      // for Web Client 2 Scheme = Bearer
      app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
      {
           ...
      });
    

    You just need to use ActiveAuthenticationSchemes like below:

     [Authorize(ActiveAuthenticationSchemes = "Cookies, Bearer")]
     public IActionResult GetCourses(){ ... }
    

    For more info see https://docs.asp.net/en/latest/security/authorization/limitingidentitybyscheme.html