如何在同一个应用程序中验证/授权MVC Web应用程序和Web API

时间:2017-07-17 10:17:02

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

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

谢谢, Tamilselvan S.

1 个答案:

答案 0 :(得分:1)

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

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,
        }

    });