我有一个建立在OWIN
和Identity
之上的API(我按照这里的教程)。 这很好用,我有一个http://my.domain.com/token
端点,返回一个承载访问令牌 。
我现在正在构建一个MVC
我们的应用程序,它将访问API以通过标准的jQuery ajax调用来记录用户。 但是一旦调用了http://my.domain.com/token
端点并从API返回了访问令牌,我该如何以我的MVC Web应用程序知道用户身份验证的方式存储此值?
我希望我的Web应用程序能够利用MVC身份功能,例如角色,以便我可以执行以下代码:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult CompanySecrets()
{
return View();
}
[Authorize(Users="Stephen")]
public ActionResult StephenSecrets()
{
return View();
}
[Authorize(Roles = "Administrators")]
public ActionResult AdministratorSecrets()
{
return View();
}
}
所以我的问题是: 如何从我的Web API存储返回的访问令牌并告诉我的MVC Web应用程序验证成功?
我正面临一个项目的相同场景。 就我而言,我已经能够通过遵循本教程来实现您可能想要实现的目标: http : //bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in -Asp净web的API-和身份-2 /
如果您查看上面的链接,您会发现非常有用的信息以及有关OAuth的概念说明(这对我很有帮助)。 我接下来要做的是使用此配置创建Web App
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
然后,在我的帐户控制器中,我只创建一个Microsoft.AspNet.Identity.UserManager
实例,并在Login
操作中我有:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
await SignInAsync(user, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "Invalid username or password.");
}
}
return View(model);
}
这种方法的问题是我正在实现的UserManager
直接进入数据库以查找有关用户的信息。 换句话说,我没有使用API,也没有使用访问令牌。 Web Api为我提供访问令牌,但我仅将它们用于移动设备和其他东西。
我现在的想法是:
Login
操作中,向Web Api发出http请求以获取令牌 System.Security.Claims.ClaimsIdentity
HttpContext.GetOwinContext().Authentication.SignIn
方法来指示用户已经过身份验证 这只是在我的脑海里。 我还在研究过程中,但我必须尽快实施。 我希望这可以给你一些更多的线索,也许比这更能让你想到的东西(你和我们分享)。
如何查看您在依赖于构建Web API的系列中的最新帖子 ,您可以将您的MVC应用程序视为您的资源服务器,但在我的解决方案中,我只使用承载令牌进行身份验证,没有cookie我的资源服务器。 我相信它应该也可以使用,您可以从授权角色中受益。
我建议您查看Identity团队的预发布版,以推动更快的原型设计。
除此之外,我建议你从这里开始,它将为你提供MVC和.NET的良好基础。 : http : //www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started
您可以通过在声明中添加标记来使用AuthenticationManager.SignIn
方法。 然后这些声明可以在MVC应用程序中使用
例
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent },
await user.GenerateUserIdentityAsync(UserManager));