简体   繁体   English

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

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

I have an API that is built on top of OWIN and Identity (I followed the tutorial here ). 我有一个建立在OWINIdentity之上的API(我按照这里的教程)。 This works great, and I have a http://my.domain.com/token endpoint that returns a bearer access token . 这很好用,我有一个http://my.domain.com/token端点,返回一个承载访问令牌

I am now building an MVC we app that will access the API to log a user in via a standard jQuery ajax call. 我现在正在构建一个MVC我们的应用程序,它将访问API以通过标准的jQuery ajax调用来记录用户。 But once the http://my.domain.com/token endpoint is called and an access token is returned from the API, how do I store this value in a way that my MVC web app knows the user is authenticated? 但是一旦调用了http://my.domain.com/token端点并从API返回了访问令牌,我该如何以我的MVC Web应用程序知道用户身份验证的方式存储此值?

I would like my web app to be able to take advantage of the MVC Identity features, such as Roles, so that I can do something like the following code: 我希望我的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();
        }

    }

So my question is: how can I store a returned access token from my web API and tell my MVC web app that the authentication was successful??? 所以我的问题是: 如何从我的Web API存储返回的访问令牌并告诉我的MVC Web应用程序验证成功?

I am facing the same scenario for a project. 我正面临一个项目的相同场景。 In my case, I've been able to implement what you might be trying to accomplish by following this tutorial: http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/ 就我而言,我已经能够通过遵循本教程来实现您可能想要实现的目标: http//bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in -Asp净web的API-和身份-2 /

If you look at the link above you will find very useful information and also concept clarification about OAuth (which really helped me). 如果您查看上面的链接,您会发现非常有用的信息以及有关OAuth的概念说明(这对我很有帮助)。 The next thing I did was to create a Web App using this configuration 我接下来要做的是使用此配置创建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);
    }

Then, in my Account Controller I just make an instance of Microsoft.AspNet.Identity.UserManager and at the Login action I have this: 然后,在我的帐户控制器中,我只创建一个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);
    } 

The problem with this approach is that the UserManager I am implementing is going directly to the database in order to find information about the user. 这种方法的问题是我正在实现的UserManager直接进入数据库以查找有关用户的信息。 In other words, I am not using the API, neither an access token. 换句话说,我没有使用API​​,也没有使用访问令牌。 The Web Api is providing me access tokens but I am using them only for Mobile Devices and other stuff. Web Api为我提供访问令牌,但我仅将它们用于移动设备和其他东西。

The approach in my mind right now is: 我现在的想法是:

  1. At the Login action, make an http request to the Web Api to get the token 在“ Login操作中,向Web Api发出http请求以获取令牌
  2. Once I have a valid token, I can set the System.Security.Claims.ClaimsIdentity for current user using the information from the token 获得有效令牌后,我可以使用令牌中的信息为当前用户设置System.Security.Claims.ClaimsIdentity
  3. Then I could use HttpContext.GetOwinContext().Authentication.SignIn method to indicate the user has been authenticated 然后我可以使用HttpContext.GetOwinContext().Authentication.SignIn方法来指示用户已经过身份验证
  4. Finally, I could save the AccessToken and its Refresh token locally using HTML5 storage API. 最后,我可以使用HTML5存储API在本地保存AccessToken及其Refresh标记。 That way I can continue consuming the Web Api directly from javascript and having Authorization features working on my Web App 这样我就可以直接从javascript继续使用Web Api并在我的Web App上使用授权功能

This is only in my mind. 这只是在我的脑海里。 I'm still in the process of research but I will have to implement something soon. 我还在研究过程中,但我必须尽快实施。 I hope this can give you some more clues and maybe something come to your mind better than this (and you share it with us). 我希望这可以给你一些更多的线索,也许比这更能让你想到的东西(你和我们分享)。

How about to look at my latest post in the series you depend on to build you Web API, you can consider your MVC app as your Resource Server, but in my solution I'm only using bearer tokens for authentication, there is no cookies in my resource server. 如何查看您在依赖于构建Web API的系列中的最新帖子 ,您可以将您的MVC应用程序视为您的资源服务器,但在我的解决方案中,我只使用承载令牌进行身份验证,没有cookie我的资源服务器。 I believe it should work as well you can benefit from the roles for Authorization. 我相信它应该也可以使用,您可以从授权角色中受益。

I suggest you look into the pre-release by the Identity team to push faster prototyping. 我建议您查看Identity团队的预发布版,以推动更快的原型设计。

Other than that I suggest you start here, it will give you a great base for MVC and .NET. 除此之外,我建议你从这里开始,它将为你提供MVC和.NET的良好基础。 : http://www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started http//www.asp.net/mvc/tutorials/mvc-5/introduction/getting-started

You can use AuthenticationManager.SignIn method by adding token in claims. 您可以通过在声明中添加标记来使用AuthenticationManager.SignIn方法。 Then those claims could be use across MVC application 然后这些声明可以在MVC应用程序中使用

Example

AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, 
await user.GenerateUserIdentityAsync(UserManager));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Azure AD - 在 C# Web API 中使用来自 Angular SPA 的图 API 访问令牌 - Azure AD - Using Graph API access token from Angular SPA in C# Web API 我的C#MVC Web应用程序API的URI是什么? - What is my C# MVC Web app api's URI? 在PHP网站上从C#WPF进行身份验证的最佳方法 - Best way to authenticate from C# WPF on PHP website 在WEB API C#应用程序层中存储和访问HTML模板的最佳方法 - Best way to Store & Access HTML Templates in WEB API C# Application Layer 验证站点/应用程序以访问Web API服务 - Authenticate a site/app to access a Web API Service 如何在IIS 6.0中正确启用匿名访问并通过c#console app使用MVC Web API? - How to properly enable Anonymous Access in IIS 6.0 & consume an MVC Web API via c# console app? 使用来自Web API的访问令牌在Web应用上授权 - Authorize at web app with access token from web api 使用Web API 2 C#处理通过请求发送的错误access_token - Handle bad access_token sent through request using Web API 2 C# 如何在Web API C#中缓存授权访问令牌? - How to do caching of Authorization access token in web api C#? 使用AutoRest C#客户端访问带有承载令牌的Web API-TokenCredentials不起作用 - Using an AutoRest C# client to access a Web API with a bearer token - TokenCredentials does not work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM