MVC4 - 通过http POST和FormsAuthentication进行Android身份验证

时间:2014-10-11 23:46:03

标签: android asp.net asp.net-mvc cookies forms-authentication

我知道网上有很多这样的资源,而我最接近的就是这个问题的答案:ASP.NET Web API Authentication

基本上,这是我的要求。在我创建的MVC4互联网应用程序(使用SimpleMembership)上通过android登录我的帐户。它不是一个MVC Web Api应用程序,在查看实现此目的的各种方法时似乎会混淆。

我正在尝试使用FormsAuthentication来设置身份验证cookie,但我不知道如何配置我的android httpclient实际发送通过此身份验证cookie,或者如何让MVC从我的Android应用程序中保存会话。

到目前为止,这是我在MVC方面提出的:

    [HttpPost]
    [AllowAnonymous]
    public bool LoginMobi(LoginModel model)
    {    
        var membership = (SimpleMembershipProvider)Membership.Provider;
        if (membership.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, false);            
            return true;
        }
        else return false;
    }

我在我的Android应用程序中使用以下java(通过SSL连接发送):

            DefaultHttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("https://mysite/api/login");
            List<NameValuePair> nameValue = new ArrayList<NameValuePair>();
            nameValue.add(new BasicNameValuePair("UserName", "foo"));
            nameValue.add(new BasicNameValuePair("Password", "bar"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValue));
            httppost.setHeader("Content-type", "application/json");
            HttpResponse response = httpclient.execute(httppost);
            // etc etc

我还没想到的是如何在android上接收身份验证cookie,并将每个请求发回给具有[Authorize]属性的控制器。我对此很新,所以请原谅我的无知!

1 个答案:

答案 0 :(得分:0)

您正在使用FormsAuthentication,它使用cookie来识别每个请求的用户。你有两个选择。

  1. 将CookieStore用于HttpClient。查看Android HttpClient and Cookies

    或者

  2. 结合BASIC auth和FormsAuthentication。查看Combining Forms Authentication and Basic Authentication

  3. 希望这有帮助。