[英].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. 我有一个使用基于标准角色的授权和JWT的API。 I need to allow specific domains to use the API without providing JWT while still continue to using role based auth for other users.
我需要允许特定域在不提供JWT的情况下使用API,同时仍继续为其他用户使用基于角色的身份验证。 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: 在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.