簡體   English   中英

使用我的API中的訪問令牌對C#MVC Web應用程序進行身份驗證的最佳方法

[英]Best way to authenticate a C# MVC web app using an access token from my API

我有一個建立在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應用程序驗證成功?

我正面臨一個項目的相同場景。 就我而言,我已經能夠通過遵循本教程來實現您可能想要實現的目標: 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上使用授權功能

這只是在我的腦海里。 我還在研究過程中,但我必須盡快實施。 我希望這可以給你一些更多的線索,也許比這更能讓你想到的東西(你和我們分享)。

如何查看您在依賴於構建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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM