Web Api 2与用户无国籍

时间:2014-07-01 16:52:37

标签: c# asp.net rest asp.net-web-api stateless

我相信我理解无会话/无状态REST的基础知识但是我在Asp.Net Web Api 2中遇到了问题,因为我之前没有使用它。我已经设置了ApiControllers,它使用像这样的自定义System.Web.Http.AuthorizeAttribute。

public class ApiAuthorizeAttribute : System.Web.Http.AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
            if (actionContext.Request.Headers.Authorization != null)
            {
                //Set identity??
                return;
            }
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
    }
}

我有一个包含用户的数据库,我需要使用它们获取/发布/放置/删除内容的权限,但不想使用会话。我从未使用过asp.net Identity,所以我不熟悉它的特性和功能。

我的实现想法是使用用户凭据或api secret签名来为每个请求进行身份验证并获得用户的权限。问题是,通过使用AuthorizeAttribute或类似的东西,如果他们的凭据是正确的,我如何在一个请求期间向控制器提供用户信息?

更新: 是使用this.User(ApiController.User)会话还是可以用于该单个请求。如果是这样,如何设置它

2 个答案:

答案 0 :(得分:1)

您可以使用HttpContext.Items保存当前请求的用户数据。 根据Auth标头设置标识后,您可以

System.Web.HttpContext.Current.Items["userdata"]=userDataObject, 

另一种方法是编写自己的动作过滤器进行身份验证(但要小心)并将数据传递给控制器​​。

public class MyAuthAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
       //do authorization here     

        base.OnActionExecuting(filterContext);

        // Create object parameter.
        filterContext.ActionParameters["userdata"] = new User("John", "Smith");

    }
}

然后在控制器

[MyAuthAttribute]
ActionResult SomeAction(User userdata) //this will have user data
{

}

答案 1 :(得分:1)

看起来使用IPrincipal并设置HttpContext.Current.User将允许ApiControllers通过使用

访问该用户
this.User

web api无法访问会话

public override void OnAuthorization(HttpActionContext actionContext)
{
        if (actionContext.Request.Headers.Authorization != null)
        {
            //Check user credentials/token here
            //Get internal user

            IPrincipal principal = new MyOwnCustomPrincipal(internalUser);
            HttpContext.Current.User = principal;
            return;
        }
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}