使用模板代码(项目模板),我创建了一个带有登录的.net核心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; }
}
我可以从登录网页登录。
我想在这个项目中使用带有授权属性的控制器(as API),这个项目来自一个桌面.net c#程序。为此,我计划从登录控制器获得一个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;
//IT在这里停留,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类具有与webapp相同的属性。
不幸的是,它不能工作,HTTP响应是400。
问题:
发布于 2016-08-13 13:17:23
我的逻辑还好吗?如果是,你能指出代码哪里出错了吗?
如果您的API期望数据为JSON,那么您可能必须适当地设置ContentType
头:
http.ContentType = "application/json";
(如果您仍然将400
作为状态代码,请检查来自API的关于您发送错误的任何提示的响应)。
基于cookie的身份验证可以访问Restful吗?
这是可能的,但可能不是最好的方法,特别是在非浏览器客户端。现在访问受保护的API的一个流行选择是通过Bearer令牌。您可以从身份提供程序端点(您的应用程序或第三方提供程序(如Auth0或StormPath) )获得令牌,并且在对API的每个请求中都将该令牌包含在Authorization
头中。有关这方面的一些讨论,请参见https://auth0.com/blog/cookies-vs-tokens-definitive-guide/。
您的API必须准备接受承载令牌作为授权访问的另一种方式。在HTTP的情况下,一些中间件将检查header中的传入令牌,验证它,并设置.Net,以便您的Authorize
属性继续按预期工作。
通常,令牌是可以检查和调试的JWTs (Json Web令牌) (它们是签名的,而不是加密的),这是使用cookie更好的体验。例如,您可以查看令牌是否过期,并获得一个新的令牌,从而避免API中的错误。
考虑到它将是HTTPS,它是否可以用于低贸易量的will服务?
它可以,但是,同样,只有当您无法控制您的API来添加对令牌的支持时,才能做到这一点。
有没有更好的方法来做到这一点,没有任何第三方提供商,如频闪路径或auth0?
JWT格式是开放和标准的。您可能会生成您的所有权,并从您需要构建的身份验证API中返回它们(这将返回令牌而不是会话cookie)。
一旦您拥有了JWT,Microsoft提供了一个包,它将帮助您使用JWT令牌保护您的API:
Install-Package Microsoft.AspNetCore.Authentication.Jwt
然而,身份验证很容易出错。这是第三方供应商,如风暴路径或Auth0将非常有用。免责声明:我为Auth0工作。
https://stackoverflow.com/questions/38922752
复制