Authentication .Net核心web api-基于角色的授权(允许特定域而无需询问JWT)

Authentication .Net核心web api-基于角色的授权(允许特定域而无需询问JWT),authentication,asp.net-web-api,asp.net-core,jwt,roles,Authentication,Asp.net Web Api,Asp.net Core,Jwt,Roles,我有一个API,它使用标准的基于角色的授权和JWT。我需要允许特定域在不提供JWT的情况下使用API,同时继续为其他用户使用基于角色的身份验证。有办法做到这一点吗?如果存在这种方式,我可以为这些域分配角色吗?您可以使用授权筛选器。当需要授权时,将执行筛选器。在筛选器中,您可以验证域并设置当前用户,包括roless: //using System; //using System.Collections.Generic; //using System.Security.Claims; //using

我有一个API,它使用标准的基于角色的授权和JWT。我需要允许特定域在不提供JWT的情况下使用API,同时继续为其他用户使用基于角色的身份验证。有办法做到这一点吗?如果存在这种方式,我可以为这些域分配角色吗?

您可以使用授权筛选器。当需要授权时,将执行筛选器。在筛选器中,您可以验证域并设置当前用户,包括roless:

//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;
    }

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

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

        // ...
    }
}