使用我的API中的访问令牌对C#MVC Web应用程序进行身份验证的最佳方法

问题描述 投票:4回答:4

我有一个建立在OWINIdentity之上的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应用程序验证成功?

c# asp.net-mvc owin
4个回答
2
投票

我正面临一个项目的相同场景。 就我而言,我已经能够通过遵循本教程来实现您可能想要实现的目标: 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为我提供访问令牌,但我仅将它们用于移动设备和其他东西。

我现在的想法是:

  1. 在“ Login操作中,向Web Api发出http请求以获取令牌
  2. 获得有效令牌后,我可以使用令牌中的信息为当前用户设置System.Security.Claims.ClaimsIdentity
  3. 然后我可以使用HttpContext.GetOwinContext().Authentication.SignIn方法来指示用户已经过身份验证
  4. 最后,我可以使用HTML5存储API在本地保存AccessToken及其Refresh标记。 这样我就可以直接从javascript继续使用Web Api并在我的Web App上使用授权功能

这只是在我的脑海里。 我还在研究过程中,但我必须尽快实施。 我希望这可以给你一些更多的线索,也许比这更能让你想到的东西(你和我们分享)。


1
投票

如何查看您在依赖于构建Web API的系列中的最新帖子 ,您可以将您的MVC应用程序视为您的资源服务器,但在我的解决方案中,我只使用承载令牌进行身份验证,没有cookie我的资源服务器。 我相信它应该也可以使用,您可以从授权角色中受益。


0
投票

我建议您查看Identity团队的预发布版,以推动更快的原型设计。

除此之外,我建议你从这里开始,它将为你提供MVC和.NET的良好基础。 : http//www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started


0
投票

您可以通过在声明中添加标记来使用AuthenticationManager.SignIn方法。 然后这些声明可以在MVC应用程序中使用

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, 
await user.GenerateUserIdentityAsync(UserManager));
© www.soinside.com 2019 - 2024. All rights reserved.