簡體   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