身份验证失败的WindowsAzureActiveDirectoryBearerAuthenticationOptions重定向

时间:2017-07-12 18:21:38

标签: azure-active-directory alexa bearer-token

我有一个MVC应用程序,也提供alexa技能。 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身份验证,我无法在身份验证失败的情况下执行自定义操作。当发生这种情况时,我需要返回对alexa的响应,而WindowsAzureActiveDirectoryBearerAuthenticationOptions与OpenIdConnectAuthenticationNotifications.AuthenticationFailed方法没有任何相似之处。 如何将自定义回复发送回alexa?

1 个答案:

答案 0 :(得分:1)

要自定义未经授权的Web 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" };
    }    

}