ASP.NET MVC - HTTP身份验证提示

zan*_*ona 27 authentication asp.net-mvc http basic-authentication

在呈现视图之前,是否可以让我的应用程序询问用户名和密码提示?就像在twitter API上获取有关您帐户的信息一样:

http://twitter.com/account/verify_credentials.xml

所以在渲染视图之前|| 文件它要求您插入用户名和密码,我认为这是直接在服务器上进行的,因为curl请求基于用户名:密码以及如下所示:

curl -u user:password http://twitter.com/account/verify_credentials.xml
Run Code Online (Sandbox Code Playgroud)

在我尝试使用相同的结构构建API时,我想知道如何在ASP.NET MVC C#上执行此操作.我已经在ruby rails上使用了它,它非常简单:

before_filter :authenticate

def authenticate
    authenticate_or_request_with_http_basic do |username, password|
    username == "foo" && password == "bar"
end
Run Code Online (Sandbox Code Playgroud)

我不认为[授权]过滤器是相同的,因为我认为它只是一个重定向,它将您重定向到基于帐户数据库的帐户内部控制器,在这种情况下,我将使用另一个数据库,特别是从webservice并在提交信息后进行验证.但我需要动作来要求用户并在其请求上传递凭据.

提前致谢


更新:

实际上,要请求一个需要此身份验证的页面(即Twitter),我必须在其请求中声明这一点

request.Credentials = new NetworkCredential("username", "password");
Run Code Online (Sandbox Code Playgroud)

这将反映出提示的用户名和密码.

所以,它是完全相同的,但从另一方面来说,如果可以根据请求向身份验证提示提供信息,我怎么能在请求中要求这种身份验证呢?

因此,每次有人试图通过示例向我的应用程序发出请求:

HTTP://为MyApplication /客户/ verify_credentials

它应该询问服务器提示符的用户名和密码,以便在curl上检索信息,例如它就像这样

curl -u user:password http://myapplication/clients/verify_credentials
Run Code Online (Sandbox Code Playgroud)

Çağ*_*kin 47

好吧,要要求基本身份验证,您需要返回401状态代码.但这样做会导致当前的身份验证模块执行其默认的未经授权的处理程序(对于表单身份验证,这意味着重定向到登录页面).

我写了一篇文章ActionFilterAttribte,看看我是否可以在没有安装认证模块时获得你想要的行为web.config.

public class RequireBasicAuthentication : ActionFilterAttribute {
   public override void OnActionExecuting(ActionExecutingContext filterContext) {
       var req = filterContext.HttpContext.Request;
       if (String.IsNullOrEmpty(req.Headers["Authorization"])) {
           var res = filterContext.HttpContext.Response;
           res.StatusCode = 401;
           res.AddHeader("WWW-Authenticate", "Basic realm=\"Twitter\"");
           res.End();
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

和控制器动作:

[RequireBasicAuthentication]
public ActionResult Index() {
    var cred = System.Text.ASCIIEncoding.ASCII
            .GetString(Convert.FromBase64String(
            Request.Headers["Authorization"].Substring(6)))
            .Split(':');
    var user = new { Name = cred[0], Pass = cred[1] };
    return Content(String.Format("user:{0}, password:{1}", 
        user.Name, user.Pass));
}
Run Code Online (Sandbox Code Playgroud)

该操作成功打印了我输入的用户名和密码.但我真的怀疑这是最好的方法.除了以这种方式询问用户名和密码外,你别无选择吗?