问题如下:我们有一个简单的asp.net mvc应用程序,它使用asp.net身份来验证oracle 12c实例 . 一切都按预期工作 . 但现在我们被要求构建一个Web API服务来进行身份验证并再次管理oracle的所有数据操作 . 这包括身份验证'因为用户商品就在它上面 .
对web api的请求是使用post发出的,例如:
private string MakePostRequest(LoginViewModel model)
{
string response = string.Empty;
WebRequest request = WebRequest.Create(requestUriString: "http://localhost:23346/api/login/authenticate");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
string parameters = "{\"Username\":\"" + model.Email + "\",\"Password\":\"" + model.Password + "\"}";
request.ContentLength = parameters.Length;
using (var requestWriter = new StreamWriter(request.GetRequestStream()))
{
requestWriter.Write(parameters);
requestWriter.Close();
}
using (var responseReader = new StreamReader(request.GetResponse().GetResponseStream())) {
response = responseReader.ReadToEnd();
}
return response;
}
因此,该方法(在mvc应用程序中的AccountController内)向web api发出post请求 .
这是web api控制器内部的方法(称为LoginController):
[HttpPost]
[Route("authenticate")]
public async Task<IHttpActionResult> Authenticate(LoginRequest login)
{
if (login == null)
throw new HttpResponseException(HttpStatusCode.BadRequest);
var result = await SignInManager.PasswordSignInAsync(login.Username, login.Password, isPersistent: true, shouldLockout: false);
if (result.Equals(SignInStatus.Success))
{
var token = TokenGenerator.GenerateTokenJwt(login.Username);
return Ok(token);
}
else
{
return Unauthorized();
}
}
最后......在mvc app中,AccountController在动作方法中获取对web api发出的post请求的结果,如下所示:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var resultado = MakePostRequest(model);
if (!string.IsNullOrEmpty(resultado))
{
FormsAuthentication.SetAuthCookie(model.Email, true);
var aut = HttpContext.User.Identity.IsAuthenticated;
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Intento de inicio de sesión no válido.");
return View(model);
}
}
现在的问题是:如何使用此Web API集成身份验证而不是直接集成到oracle数据库?我的意思是,当我们直接对oracle使用身份验证时,一切都按预期工作(您可以在_LoginPartial.cshtml视图中看到用户名,正如人们所期望的那样)但是当我们使用web api时,我们会收到令牌,但用户根本没有经过身份验证 . 我知道我错过了一些东西,但我没有得到它,我在这种情况下找不到任何示例(MVC对web api进行身份验证并创建cookie /sessión变量等)
如何才能做到这一点?
提前致谢 .