简体   繁体   English

MVC和WebAPI网站中的身份验证

[英]Authentication In MVC & WebAPI Website

I have a website using simple forms authentication, validating credentials with the database. 我有一个使用简单表单身份验证的网站,用于通过数据库验证凭据。 It's working fine as it is. 一切正常。 In my <system.web> within the web.config I have: web.config中的 <system.web>中,我具有:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>  

I now have the need to add a small WebApi Controller to the site for an application to pull a list of objects from. 现在,我需要向站点添加一个小型WebApi控制器,以便应用程序从中提取对象列表。 It seems like, as far as the WebApi authentication goes, Basic authentication would be fine. 就WebApi身份验证而言,基本身份验证似乎很好。 I'll have the user credentials in the application, which can easily be passed up, encoded in the request header. 我将在应用程序中拥有用户凭据,该凭据可以轻松地传递到请求标头中。

My issue is differentiating the MVC and WebApi authentication. 我的问题是区分MVC和WebApi身份验证。 First of all, is my solution a good idea, and easily implementable? 首先,我的解决方案是一个好主意并且容易实现吗? Currently, in my WebApiConfig.cs I have : 当前,在我的WebApiConfig.cs我有:

GlobalConfiguration.Configuration.MessageHandlers.Add(new BasicAuthenticationHandler(new AuthenticationService()));

and BasicAuthenticationHandler looks for the credentials in the header. 然后BasicAuthenticationHandler在标题中查找凭据。 However, with the MVC forms authentication, I'm unable to reach that area at all. 但是,使用MVC表单身份验证,我根本无法到达该区域。 When I hit the action in fiddler, I can see it redirects me straight to the MVC Account/Login page. 当我在提琴手中操作时,可以看到它将我直接重定向到“ MVC帐户/登录”页面。 How do avoid the redirection for my WebAPI calls? 如何避免WebAPI调用的重定向?

Thank you for any guidance. 感谢您的指导。

Well, looks like it was a simple fix. 好吧,看来这是一个简单的修复。 The direct line after the web.config code I have above looked like: 我上面的web.config代码后的直线如下所示:

  <authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
  </authentication>
  <authorization>
    <deny users="?" />
  </authorization>

and it looks like the authorization element was completely overwriting any [AllowAnonymous] I had - the only possible method to reach anonymously was the login page. 而且看起来authorization元素完全覆盖了我拥有的所有[AllowAnonymous] -匿名访问的唯一可能方法是登录页面。 Removing those 3 lines completely fixed my issue - I now use the [AllowAnonymous] attribute for my WebAPI page, and it applies the basic authentication correctly. 删除这三行代码可以完全解决我的问题-我现在在WebAPI页面上使用[AllowAnonymous]属性,它可以正确应用基本身份验证。

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

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