首页 文章

使用Auth标头(如webAPI)但在MVC中进行身份验证

提问于
浏览
4

好吧,读这篇文章的人可能都知道(我也是如此)WebAPI如何工作以及如何使用WebAPI和Identity框架构建应用程序我可以构建一个http请求,添加一个auth标头,应用程序将通过阅读auth知道我是谁头 .

这就是所谓的“无状态”API调用,其中接收调用的API的所有内容都被赋予了确定用户身份所需的所有内容,因此可以对用户进行身份验证并对其请求进行“无状态”操作 .

.....

我想在MVC(而不是Web API)中使用这种完全相同的行为 .

我希望以前没有对此应用程序提出任何请求,我的应用程序使用Identity框架的方式与我的WebAPI endpoints 完全相同,以确保使用Authorization标头对每个“无状态”调用进行身份验证 .

这是我在WebAPI中做的方式(在MVC中不起作用)......

using Core.App.Security;
using Microsoft.Owin.Security.OAuth;
using Ninject;
using Owin;

namespace Core.App
{
    /// <summary>
    /// Setup as per ...
    /// Source code: https://github.com/tjoudeh/AngularJSAuthentication
    /// walkthrough: http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/
    /// </summary>
    public static class Auth
    {
        public static void Configure(IAppBuilder app, IKernel kernel)
        {
            // ensure that owin creates the required UserManager & sign in manager per owin instance
            app.CreatePerOwinContext<ApplicationUserManager>((options, owinContext) => ApplicationUserManager.Create(options, owinContext, kernel));
            app.CreatePerOwinContext<ApplicationSignInManager>((options, owinContext) => ApplicationSignInManager.Create(options, owinContext, kernel));

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
            app.AddAuthInfoToContext();
        }
    }
}

本质上,这使用令牌设置承载auth,但不是当前应用程序中的auth服务器 .

这段代码允许我作为我的Auth令牌提供者的集中式SSO服务器可以发出我可以对任何API应用程序使用的令牌(是的,我有很多) .

Differences

WebAPI将在当前标识(HttpContext.Current.Identity)中具有授权用户信息,并且不依赖于会话/先前的登录调用来创建会话信息 .

MVC依赖于会话和用户采用一种更传统的“Forms Auth”类型方法,这意味着我必须在我关心的请求之前向本地MVC应用程序发出auth请求以“登录” .

So the question is

当这是该用户在该会话中发出的第一个请求时,如何在使用上述代码与Identity框架时使用WebAPI时,如何在典型的http get请求中使用授权标头令牌“登录”?

1 回答

  • 0

    使用auth标头中的令牌信息来检索用户并在管道的早期阶段将其放入当前标识(可能在auth阶段)

    当我使用owin来设置我的应用程序时,我可以轻松定义一个自定义中间件,以根据令牌信息将所需的更改应用于当前身份 .

相关问题