【发布时间】:2016-08-12 16:36:24
【问题描述】:
使用项目模板中的样板代码,我创建了一个带有登录名的 .net core mvc6 webapp。
登录控制器是:
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
LoginViewModel 是:
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
我可以从登录网页登录。
我想通过桌面 .net c# 程序在此项目中使用具有 [Authorization] 属性的控制器(作为 API)。为此,我计划从登录控制器获取 cookie 并使用 cookie 访问 API。
桌面软件获取 cookie 的代码是(复制粘贴表单 StackOverflow 并添加 JSON 序列化):
private void btnLogin_Click(object sender, EventArgs e)
{
HttpWebRequest http = WebRequest.Create(loginUrl) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
var login = new LoginViewModel();
login.Email = txtUserName.Text;
login.Password = txtPassword.Text;
var postData = new JavaScriptSerializer().Serialize(login);
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
//HTTP 400 在这里停止
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(authorized) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
}
LoginViewModel 类具有与 web 应用程序相同的属性。
不幸的是它不起作用,HTTP 响应是 400。
问题:
我的逻辑正常吗?如果是,你能指出代码哪里错了吗?
基于 cookie 的身份验证是否可以访问 Restful web api?
考虑到它将是 HTTPS,它能否用于流量较低的 Web 服务?
如果没有像 strompath 或 auth0 这样的第三方提供商,有没有更好的方法?
【问题讨论】:
标签: .net cookies authorization asp.net-core-mvc