【问题标题】:How to authenticate/Authorize the MVC web app and web api in the same application如何在同一应用程序中对 MVC Web 应用程序和 Web API 进行身份验证/授权
【发布时间】:2017-07-17 10:17:02
【问题描述】:

我们使用带有 Azure 活动目录的 asp.net MVC 框架开发了一个 Web 应用程序,用于身份验证/授权。 现在的问题是我们要在那个 webapp 中使用 api。对于 web api 的身份验证,我们是否可以使用我们成功授权 webapp web 应用时获得的请求令牌。

谢谢, Tamilselvan S.

【问题讨论】:

  • 问题解决了吗?如果没有,请随时告诉我您被阻止的步骤。

标签: c# asp.net asp.net-mvc asp.net-web-api azure-active-directory


【解决方案1】:

您可以为支持 OWIN 的 Web 应用添加多个身份验证中间件。要同时支持cookie和bear认证,可以参考以下代码:

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

app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {

        ClientId = clientId,
        Authority = Authority,
        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
            RedirectToIdentityProvider = (context) =>
            {
                // This ensures that the address used for sign in and sign out is picked up dynamically from the request
                // this allows you to deploy your app (to Azure Web Sites, for example)without having to change settings
                // Remember that the base URL of the address used here must be provisioned in Azure AD beforehand.
                string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                context.ProtocolMessage.RedirectUri = appBaseUrl + "/";
                context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                return Task.FromResult(0);
            },

            AuthenticationFailed = (context) =>
            {
                // Suppress the exception if you don't want to see the error
                context.HandleResponse();

                return Task.FromResult(0);
            }

        },
        TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
        {
            ValidateIssuer = false,
        }

    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-05
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 2017-10-29
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多