使用樣板代碼構建項目模板我使用login創建了一個.net core mvc6 webapp。.Net MVC 6來自桌面應用程序的授權
登錄控制器是:
// 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
問題:
是我的邏輯OK?如果是的話,你能指出代碼錯在哪裏嗎?
基於cookie的身份驗證是否可以訪問Restful web api?
它可以用於低流量的web服務,因爲它將是HTTPS?
有沒有更好的方式來做到這一點,沒有任何第三方提供商如strompath或auth0?