繁体   English   中英

asp.net Web api 2根据实体特定的属性值授权API(来自数据库)

[英]asp.net web api 2 authorize API depending on Entities specific property value(From Database)

我已经使用Authorize属性确保了API的安全性。

如果请求没有有效的OAuth令牌,则不处理并返回授权错误

在我的用户表中,我添加了“状态”列以检查用户是否处于活动状态(软删除)。

我想使用“状态”值(用户实体)来验证我的API。

假设Status为false,我希望框架不像“ Authorize attribute”一样处理请求。

  • 有可能吗? 如果是这样,那又如何?

注意:

现在,我在“操作”中检查“状态”值,然后决定是否继续。

如果您还有其他最佳选择,那么也欢迎您。

谢谢。

您可以实现自己的AuthorizeAttribute

这是我用来基于Roles实现我自己的Authorize方法的示例:

public class AuthorizeRoles : AuthorizeAttribute
    {
        private readonly List<string> _rolesAllowed;

        public AuthorizeRoles(string rolesAllowed)
        {
            this._rolesAllowed = rolesAllowed.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {            
            var controller = actionContext.ControllerContext.Controller;

                if (!this._rolesAllowed.Contains("*"))
                {
                    string errorMessage = "Authorization denied. Missing required role";
                    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                }

            }
            else
            {
                string errorMessage = "Authorization denied. Request is missing context header";
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }

            base.OnAuthorization(actionContext);
        }

然后,您可以在api方法中使用它,如下所示:

[AuthorizeRoles("some value")] or [AuthorizeRoles("*")]

您可以有效地指定哪些方法允许访问具有特定价值的人。

您有权访问控制器,可以检查所需的任何值,并根据检查结果允许或拒绝访问。

我已经删除了一些不太有趣的代码,但是剩下的应该可以告诉您如何继续。

我将如何创建具有不同访问级别的Roles表。 在我的控制器上,我将使用Authorize属性的Roles功能来允许或阻止用户访问Action。

[Authorize(Roles = "isActive")]

暂无
暂无

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

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