在ASP.NET的Web API用户身份验证 [英] User Authentication in ASP.NET Web API

查看:157
本文介绍了在ASP.NET的Web API用户身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个话题一直是我难以置信的混乱。我在HTTP应用新秀,但需要开发一个iPhone客户端从某处消费JSON数据。我选择的Web API从MS,因为它似乎很容易,但是当涉及到​​验证用户身份,事情就变得很沮丧。

我很惊讶,我怎么没能找到如何在用户进行身份验证直接从登录屏幕下使用授权属性在一个明显的例子,我的 ApiController 几个小时的谷歌搜索后的方法。

这是不是一个问题,但对于如何做到这一点正是一个实例的请求。我已经看过以下页面:

虽然这些解释如何处理未授权的请求,这些并没有表现出明显的东西像的LoginController 或类似的东西,要求用户凭据并验证它们。

任何人都愿意写一个不错的简单的例子,或点我在正确的方向吗?

感谢。


解决方案

  

我很惊讶,我怎么没能找到如何验证下来直接从登录屏幕的用户几个小时的谷歌搜索后,使用授权属性在我ApiController方法一个明显的例子。


那是因为你感到困惑关于这两个概念的:


  • 认证是机制,使系统可以安全地识别他们的用户。认证系统的问题提供了一个答案:


    • 用户是谁?

    • 是用户真正谁,他/她重新presents自己是?


  • 授权是通过该系统确定一个特定认证的用户应该有由系统控制确保的资源的访问级别的机制。例如,数据库管理系统可能被设计成以提供某些特定的个人使用,以从数据库检索信息的能力,但不改变存储在datbase数据的能力,同时给予其他个人改变数据的能力。授权系统的问题提供答案:


    • 是用户X授权访问资源R?

    • 是用户X授权执行运行时的P?

    • 是用户X授权对资源R进行运行时的P?


MVC中的授权属性用于应用访问规则,例如:

  [System.Web.Http.Authorize(角色=管理员,超级用户)]
 公众的ActionResult AdministratorsOnly()
 {
     返回查看();
 }

以上规则只允许管理的用户的超级用户的角色访问方法

这些规则也可以在web.config文件中设置,使用位置元素。例如:

 <位置路径=首页/ AdministratorsOnly>
    <&的System.Web GT;
      <授权>
        <让角色=管理员/>
        <拒绝用户=*/>
      < /授权>
    < /system.web>
  < /地点>

然而,执行的那些授权规则之前,你要的验证到的当前网站


  

虽然这些解释如何处理未授权的请求,这些不清楚地表明像一个LoginController中或类似的东西,要求用户凭据并验证它们。


从这里,我们可以一分为二的问题:


  • 在同一Web应用程序中使用Web API服务时,用户身份验证

    这是最简单的方法,因为你会依赖于ASP.Net 认证>

    这是一个简单的例子:

    的Web.config

     <身份验证模式=表格>
      <形式
        保护=全部
        slidingExpiration =真
        loginUrl =账号/登录
        无Cookie =UseCookies
        enableCrossAp predirects =假
        NAME =cookieName
      />
    < /认证>

    用户会被重定向到的帐户/登录的路线,有你会使自定义控件,要求用户凭据,然后你会使用设置身份验证Cookie:

     如果(ModelState.IsValid)
        {
            如果(Membership.ValidateUser(model.UserName,model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName,model.RememberMe);
                返回RedirectToAction(指数,家);
            }
            其他
            {
                ModelState.AddModelError(,提供的用户名或密码不正确。);
            }
        }    //如果我们走到这一步,事情失败了,重新显示形式
        返回查看(模型);


  • - 跨平台身份验证

    在此情况下,将只露出了Web应用程序中的Web API服务因此,你将有另一个客户消费服务,客户端可以是其他Web应用程序或任何.NET应用程序(赢形式,WPF,控制台,Windows服务等)

    例如假设你将消耗从同一网​​络域(内部网内)另一个Web应用程序的Web API服务,在这种情况下,你可以依赖于ASP.Net提供的Windows身份验证。

     <身份验证模式=窗口/>

    如果您的服务在互联网上曝光,那么你就需要经过身份验证令牌传递给每个Web API服务。

    有关更多信息,拿战利品以下文章:


    • <一个href=\"http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/\">http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/


    • <一个href=\"http://$c$cbetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/\">http://$c$cbetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/



This topic has been incredibly confusing for me. I am a rookie in HTTP apps but need to develop an iPhone client that consumes JSON data from somewhere. I chose Web API from MS because it seemed easy enough but when it comes to authenticating users, things get quite frustrating.

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

This is not a question but a request for an example of how to do this exactly. I have looked at the following pages:

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

Anyone willing to write a nice simple example or point me in the right direction, please?

Thanks.

解决方案

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

That's because you are getting confused about these two concepts:

  • Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:

    • Who is the user?
    • Is the user really who he/she represents himself to be?
  • Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:

    • Is user X authorized to access resource R?
    • Is user X authorized to perform operation P?
    • Is user X authorized to perform operation P on resource R?

The Authorize attribute in MVC is used to apply access rules, for example:

 [System.Web.Http.Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

The above rule will allow only users in the Admin and Super User roles to access the method

These rules can also be set in the web.config file, using the location element. Example:

  <location path="Home/AdministratorsOnly">
    <system.web>
      <authorization>
        <allow roles="Administrators"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

However, before those authorization rules are executed, you have to be authenticated to the current web site.

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

From here, we could split the problem in two:

  • Authenticate users when consuming the Web API services within the same Web application

    This would be the simplest approach, because you would rely on the Authentication in ASP.Net

    This is a simple example:

    Web.config

    <authentication mode="Forms">
      <forms
        protection="All"
        slidingExpiration="true"
        loginUrl="account/login"
        cookieless="UseCookies"
        enableCrossAppRedirects="false"
        name="cookieName"
      />
    </authentication>
    

    Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:

        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    

  • Cross - platform authentication

    This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)

    For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.

    <authentication mode="Windows" />
    

    If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.

    For more info, take a loot to the following articles:

这篇关于在ASP.NET的Web API用户身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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