ASP.NET Core with optional authentication/authorization

后端 未结 2 484
滥情空心
滥情空心 2020-12-21 04:39

I want to build an ASP.NET Core based WebApi for accessing data from a database. This WebApi could be used in two ways, either as a public WebApi which would need authentica

相关标签:
2条回答
  • 2020-12-21 05:11

    If you bypass authentication, how do you distinguish internal or public requests for api? This causes security bug. So you shouldn't bypass authentication.

    If you use openidconnect authentication in mvc application then you can set SaveTokens=true. It enables you to store access token in cookie. When you call api in mvc action you can send this access_token to api.

    Another way using two different authentication middleware, one for internal another for public access(This is hard to implement).

    I would go with first approach.

    Update

    To achieve your goal, a tricky way is coming to my mind but i am not sure it is good way:

    Create a filter provider:

    public class EncFilterProvider : IFilterProvider
    {
        public int Order
        {
            get
            {
                return -1500;
            }
        }
    
        public void OnProvidersExecuted(FilterProviderContext context)
        {
        }
    
        public void OnProvidersExecuting(FilterProviderContext context)
        {
            // remove authorize filters
            var authFilters = context.Results.Where(x => 
               x.Descriptor.Filter.GetType() == typeof(AuthorizeFilter)).ToList();
            foreach(var f in authFilters)
                context.Results.Remove(f);
        }
    }
    

    Then register it conditionally based on config value

      public void ConfigureServices(IServiceCollection services)
      {
          if(config["servermode"] = "internal")
          {
              services.AddScoped<IFilterProvider, EncFilterProvider>();
          }
       }
    
    0 讨论(0)
  • 2020-12-21 05:14

    I would recommend to authenticate both applications: web application and the Web API one. You will have everything secured. For skipping an authentication that is not a good idea. Simply create an user for your web application (in the Web API application) which will be used to authenticate when getting data from the Web API.

    0 讨论(0)
提交回复
热议问题