Folder authorization in asp.net Identity 2.1

六眼飞鱼酱① 提交于 2019-12-25 12:03:54

问题


I searched but couldn't find role based authorization for access to folders or files in .net identity 2.1 as there is in form based authorization

    <location path="Pictures">
   <system.web>
      <authorization>
         <allow roles="Administrators"/> //Allows users in Admin role
         <deny users="*"/> // deny everyone else
      </authorization>
   </system.web>
</location>

Is there any way to implement this in .net identity?


回答1:


You can write a filter:

public class FilterStaticFilesAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var request = actionContext.Request;

        if (request.RequestUri.LocalPath.StartsWith("\Pictures", System.StringComparison.InvariantCultureIgnoreCase))
        {
            if (!request.GetOwinContext().Authentication.User.IsInRole("Administrators"))
            {
                actionContext.Response.StatusCode = HttpStatusCode.Forbidden;
                return;
            }
        }
        base.OnAuthorization(actionContext);
    }
}

Register in WebApiConfig.Register:

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new FilterStaticFilesAttribute());
}

What this does: alle requests will pass the registered filter. Inside the filter determine if it is a call to the static files location. Only if the user has the role of Administrators then access is granted.



来源:https://stackoverflow.com/questions/43802683/folder-authorization-in-asp-net-identity-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!