【问题标题】:ASP.NET Forward userid from AuthorizeAttributeASP.NET 从 AuthorizeAttribute 转发用户 ID
【发布时间】:2013-10-02 04:32:39
【问题描述】:

我有一个 AuthorizeAttribute 类来拦截对我的 Web Api 的调用。我在给定的会话中验证用户。

如果用户拥有正确的凭据,我想在请求正文中附加在凭据检查期间获取的 userId。我尝试了一些东西,但似乎无法访问 IsAuthorized 中的请求正文?

我正在尝试做这样的事情:

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext httpContext)
    {
        // Pick up session
        var sessionKey = httpContext.Request.Headers.FirstOrDefault(h => h.Key == "session").Value;

        // If session vas valid, get userid from session and add it to the request body somehow
        // so the controller gets userid attached.

        return true;
    }
} 

之后,目标控制器被调用:

public Response GetCandy( CandyRequest candy )
{
    // Wohoo, the user was accepted and i've got the user id already in the argument object.
    var userId = candy.UserId;
}

【问题讨论】:

    标签: c# asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    我不确定我是否完全理解您在此寻找的内容。如果您尝试访问candy 并从您的属性中设置UserId,您可能会遇到困难。在模型绑定碰巧注入您的用户 ID 之前,您也许可以添加它以使用 httpContext.ActionArguements 执行某些操作。

    但是,我一直将 AuthorizeAttribute 理解为一个看门人,不应该在其中设置数据。话虽如此,一种解决方法是您可以使用HttpContext.Items 为请求设置项目,因此您的结果代码看起来像

    protected override bool IsAuthorized(HttpActionContext httpContext)
    {
        // code to map the session to the user.
    
        HttpContext.Current.Items["UserId"] = 23423; // set the user id to the Items collection
    
        return true;
    }
    

    然后在你的控制器中

    public Response GetCandy( CandyRequest candy )
    {
        // Wohoo, the user was accepted and i've got the user id already in the argument object.
        var userId = HttpContext.Items["UserId"];
    }
    

    【讨论】:

    • 谢谢,这是为我做的。
    猜你喜欢
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2013-06-13
    • 2011-07-24
    • 2016-11-15
    • 1970-01-01
    • 2012-03-20
    • 2019-08-06
    相关资源
    最近更新 更多