OWIN:未经授权的WebAPI调用返回的登录页面,而不是401 [英] OWIN: unauthorised webapi call returning login page rather than 401

查看:666
本文介绍了OWIN:未经授权的WebAPI调用返回的登录页面,而不是401的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何配置我的MVC /的​​WebAPI项目,以便从剃刀视图称为的WebAPI方法不返回loginpage时,其未经授权的?

How do I configure my mvc/webapi project so that a webapi method called from a razor view doesn't return the loginpage when its unauthorised?

它是一个MVC5应用程序,还具有的WebAPI控制器,​​用于通过JavaScript调用。

Its a MVC5 application which also has WebApi controllers for calls via javascript.

这两种方法如下

[Route("api/home/LatestProblems")]      
[HttpGet()]
public List<vmLatestProblems> LatestProblems()
{
    // Something here
}

[Route("api/home/myLatestProblems")]
[HttpGet()]
[Authorize(Roles = "Member")]
public List<vmLatestProblems> mylatestproblems()
{
   // Something there
}

通过以下角度code被称为:

are called via the following angular code:

angular.module('appWorship').controller('latest', 
    ['$scope', '$http', function ($scope,$http) {         
        var urlBase = baseurl + '/api/home/LatestProblems';
        $http.get(urlBase).success(function (data) {
            $scope.data = data;
        }).error(function (data) {
            console.log(data);
        });
        $http.get(baseurl + '/api/home/mylatestproblems')
          .success(function (data) {
            $scope.data2 = data;
        }).error(function (data) {
            console.log(data);
        });  
    }]
);

所以我没有登录和第一种方法成功返回的数据。第二种方法返回(在成功函数),其中包含的登录页面的等效数据。即,你会得到什么MVC中,如果你要求的,将其用[授权]印记的控制器操作,你没有登录。

So I'm not logged in and the first method successfully returns data. the second method returns (in the success function) data which contains the equivalent of a login page. i.e. what you would get in mvc if you requested a controller action which was stamped with [Authorize] and you weren't logged in.

我希望它返回一个401未经授权,这样我可以根据他们是否已登录或没有用户显示不同的数据。理想情况下,如果用户登录我希望能够访问控制器的用户属性,这样我就可以返回特定会员数据。

I want it to return a 401 unauthorized, so that i can display different data for users based on if they are logged in or not. Ideally if the user is logged in i want to be able to access the Controller's User property so i can return data specific to that Member.

更新:由于没有下面的建议似乎不再起作用(以身份或改变的WebAPI)香港专业教育学院创建于 github上一个原始的例子这应该说明问题。

UPDATE: Since none of the suggestions below seem to work anymore (changes to Identity or WebAPI) ive created a raw example on github which should illustrate the problem.

推荐答案

有两种AuthorizeAttribute实现,你需要确保你所引用正确的用于Web的API。有<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.http.authorizeattribute%28v=vs.108%29.aspx\">System.Web.Http.AuthorizeAttribute这是用于Web的API和<一href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute%28v=vs.108%29.aspx\">System.Web.Mvc.AuthorizeAttribute它是用来与视图控制器。的 Http.AuthorizeAttribute 的会,如果授权失败的 Mvc.AuthorizeAttribute 的会重定向到登录页面,返回401错误。

There are two AuthorizeAttribute implementations and you need to make sure you are referencing the correct one for Web API's. There is System.Web.Http.AuthorizeAttribute which is used for Web API's, and System.Web.Mvc.AuthorizeAttribute which is used for controllers with views. Http.AuthorizeAttribute will return a 401 error if authorization fails and Mvc.AuthorizeAttribute will redirect to the login page.

更新2013年11月26日

因此​​,它似乎事情已经彻底与MVC 5变更为布鲁克·艾伦指出,<一个href=\"http://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-$c$cs/\">in他的文章。我猜OWIN管道接管并引入了一些新的行为。现在,当用户没有被授权为200的状态返回与在HTTP头中的以下信息。

So it appears things have drastically changed with MVC 5 as Brock Allen pointed out in his article. I guess the OWIN pipeline takes over and introduces some new behavior. Now when the user is not authorized a status of 200 is returned with the following information in the HTTP header.

X-Responded-JSON: {"status":401,"headers":{"location":"http:\/\/localhost:59540\/Account\/Login?ReturnUrl=%2Fapi%2FTestBasic"}}

您可以改变客户端上你的逻辑在头检查这些信息来确定如何处理这个问题,而不是找上的错误分支401状态。

You could change your logic on the client side to check this information in the header to determine how to handle this, instead of looking for a 401 status on the error branch.

我试图通过在 OnAuthorization 的响应状态设置为覆盖在自定义的 AuthorizeAttribute 的这种行为和 HandleUnauthorizedRequest 的方法。

I tried to override this behavior in a custom AuthorizeAttribute by setting the status in the response in the OnAuthorization and HandleUnauthorizedRequest methods.

actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);

但是,这并不工作。新管道以后必须抓住这个响应,并将其修改为我之前得到同样的反应。投掷,因为它只是变成了一个500错误状态的HttpException没有工作,要么。

But this did not work. The new pipeline must grab this response later and modify it to the same response I was getting before. Throwing an HttpException did not work either as it is just changed into a 500 error status.

我测试了布鲁克·艾伦的解决方案,它是我用jQuery的AJAX调用时所做的工作。如果它不为你工作我的猜测是,这是因为你使用的角度。使用Fiddler运行测试,看看下面是你的头。

I tested Brock Allen's solution and it did work when I was using a jQuery ajax call. If it is not working for you my guess is that it is because you are using angular. Run your test with Fiddler and see if the following is in your header.

X-Requested-With: XMLHttpRequest

如果它不是那么这就是问题所在。我不熟悉的角度,但如果它让你插入自己的头值,然后添加到您的Ajax请求,它可能会开始工作。

If it is not then that is the problem. I am not familiar with angular but if it lets you insert your own header values then add this to your ajax requests and it will probably start working.

这篇关于OWIN:未经授权的WebAPI调用返回的登录页面,而不是401的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆