Перенаправление WindowsAzureActiveDirectoryBearerAuthenticationOptions при сбое проверки подлинности

У меня есть приложение MVC, которое также обслуживает навык Алекса. Аутентификация для навыка alexa выполняется с использованием WindowsAzureActiveDirectoryBearerAuthentication следующим образом:

 app.Use(typeof(AlexaJWTMiddleware));
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = domain,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = ConfigurationManager.AppSettings["ida:AppIdUri"]
                },
                AuthenticationType = "OAuth2Bearer",
            });

и затем идет аутентификация для части MVC, которая выполняется следующим образом:

   app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            // This is NOT ASP.NET Session Timeout (that should be set to same value in web.config)
            // This is the expiration on the cookie that holds the Azure AD token
            ExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(expirationTimeSpan)),

            // Set SlidingExpiration=true to instruct the middleware to re-issue a new cookie
            // with a new expiration time any time it processes a request which is more than
            // halfway through the expiration window.
            SlidingExpiration = true,

            Provider = new CookieAuthenticationProvider
            {
                // This method is called every time the cookie is authenticated, which
                // is every time a request is made to the web app
                OnValidateIdentity = CookieAuthNotification.OnValidateIdentity
            }
        });

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                UseTokenLifetime = false,
                /*
                * Skipping the Home Realm Discovery Page in Azure AD
                * http://www.cloudidentity.com/blog/2014/11/17/skipping-the-home-realm-discovery-page-in-azure-ad/
                */
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = OpenIdConnectNotification.RedirectToIdentityProvider,
                    MessageReceived = OpenIdConnectNotification.MessageReceived,
                    SecurityTokenReceived = OpenIdConnectNotification.SecurityTokenReceived,
                    SecurityTokenValidated = OpenIdConnectNotification.SecurityTokenValidated,
                    AuthorizationCodeReceived = OpenIdConnectNotification.AuthorizationCodeReceived,
                    AuthenticationFailed = OpenIdConnectNotification.AuthenticationFailed
                },

            });

Все работает нормально, но для аутентификации alexa у меня нет способа выполнить пользовательское действие в случае сбоя аутентификации. Мне нужно вернуть ответ Алексе, когда это произойдет, и WindowsAzureActiveDirectoryBearerAuthenticationOptions не имеет ничего похожего на метод OpenIdConnectAuthenticationNotifications.AuthenticationFailed. Как я могу отправить индивидуальный ответ обратно Алексе?

1 ответ

Решение

Чтобы настроить неавторизованный запрос для веб-API, мы можем создать собственный атрибут авторизации, как показано ниже:

public class CustomAuthorization : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response = new HttpResponseMessage
        {
            StatusCode = HttpStatusCode.Unauthorized,
            Content = new StringContent("You are unauthorized to access this resource!")
        };
    }
}

[CustomAuthorization]
public class ValuesController : ApiController
{
    public ValuesController()
    {
    }

    // GET api/values
    public IEnumerable<string> Get()
    {       
        return new string[] { "value1", "value2" };
    }    

}
Другие вопросы по тегам