.Net core web api - 基于角色的授权(允许特定域名而不询问JWT)

问题描述 投票:0回答:1

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

authentication asp.net-web-api asp.net-core jwt roles
1个回答
1
投票

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

//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());

        // ...
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.