【问题标题】:Use both cookie based authentication and token based authentication for api controllers对 api 控制器使用基于 cookie 的身份验证和基于令牌的身份验证
【发布时间】:2021-02-08 22:36:18
【问题描述】:

我们有一个应用程序,它也有一些应该使用身份验证令牌调用的 api 控制器,还有一些其他 api/常规控制器应该使用基于开放 id 连接 cookie 的身份验证。下面是来自 Startup.Auth.cs 的代码

public void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseKentorOwinCookieSaver();
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        { CookieSecure = CookieSecureOption.Always });

        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(PasswordResetPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpSignInPolicyId));

        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                },
            });
    }

我们有一个差异窗口应用程序,在添加用户凭据后应该使用令牌调用 api 控制器方法。它确实调用了 api 方法,但作为响应,我们得到了一个 html 登录页面 ui 代码。收到 OK 状态,但我们应该获取 api 方法返回的值,而不是这个登录页面代码。此方法不会被执行,因为身份验证会以某种方式产生问题。

【问题讨论】:

    标签: asp.net-mvc api openid-connect azure-ad-b2c azure-authentication


    【解决方案1】:

    我的目标是确保网络和应用程序之间的清晰分离,遵循以下原则:

    网络应用程序特征

    • 使用网络托管解决方案
    • 当请求未获授权时,将 OAuth 重定向返回给调用者

    API 特性

    • 使用 API 托管解决方案
    • 请求未获授权时向调用者返回 401 响应

    这将解决您的桌面应用程序的问题。

    代码分离

    旨在将您的 Web 后端和 API 代码分开 - 在物理上作为单独的组件,或在逻辑上在同一组件内。如果是后者,惯例通常是为 API 端点使用 /api 根路径:

    • /myapp/myWebPage1
    • /myapp/myWebPage2
    • /myapp/api/myOperation1
    • /myapp/api/myOperation2

    微软解决方案

    在 .Net Core 中,微软的 UseWhen 机制运行良好,因此您可以编写如下代码:

    app.UseWhen(
      ctx => ctx.Request.Path.StartsWithSegments(new PathString("/api")),
      api => app. UseWindowsAzureActiveDirectoryBearerAuthentication()
    );
    app.UseWhen(
      ctx => !ctx.Request.Path.StartsWithSegments(new PathString("/api")),
      api => app. UseCookieAuthentication()
    );
    

    如果您使用的是基于 OWIN 的 C#,则可以通过 extension method similar to this 实现相同的模式。

    【讨论】:

      猜你喜欢
      • 2021-01-25
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2014-05-28
      • 2020-10-08
      • 2015-10-29
      • 2017-11-27
      相关资源
      最近更新 更多