简体   繁体   中英

.Net core web api - Role based authorization (Allow specific domains without asking JWT)

I have an API that uses standard role based authorization and JWT. I need to allow specific domains to use the API without providing JWT while still continue to using role based auth for other users. Is there a way to do this? Can I assign roles to these domains if such a way exists?

You can use an authorization filter. When authorization is required, the filter is executed. In the filter you can validate the domain an set the current user, including the roles(s):

//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Security.Principal;
//using System.Web;
//using System.Web.Http.Controllers;
//using System.Web.Http.Filters;

public class AddIdentityFilter : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var allowedIpAdresses = new List<string> { "127.0.0.1", "" };
        // Replace with your code to test the domain
        var isInDomain = allowedIpAdresses.Contains(GetIp());
        var identity = HttpContext.Current.User.Identity;

        if (!identity.IsAuthenticated && isInDomain)
        {
            // Add the roles to the new Identity
            HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("DomainUser"), new[] { "Admin" });
        }
        base.OnAuthorization(actionContext);
    }

    // Helper to determine the ipaddress
    private string GetIp()
    {
        var context = (HttpContextBase)HttpContext.Current.Items["MS_HttpContext"];
        if (context != null)
            return context.Request.UserHostAddress;

        if (HttpContext.Current != null)
            return HttpContext.Current.Request.UserHostAddress;

        return null;
    }

}

In WebApiConfig.cs add the filter:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Only needed for Owin
        config.SuppressDefaultHostAuthentication();

        config.Filters.Add(new AddIdentityFilter());

        // ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM