繁体   English   中英

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

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

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

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

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

}

在WebApiConfig.cs中添加过滤器:

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

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

        // ...
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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