CB4
CB4

Reputation: 748

OAuth bearer-token log for debug

I have a .net Rest API and I am using Azure ADD for OAuth.

In Startup.cs I have this:

public void Configuration(IAppBuilder app)
{
    ConfigureAuth(app);
}

In Startup.Auth.cs I have this: (obviously I have add my Azure app information in the AppSettings)

// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                }
            });
    }

And, in my API Controller.cs I have added the [Authorize] attribute.

    [Authorize]
    public class ApplicationsController : ApiController
    {
        //...my stuff goes here
    }

A client application would get a bear-token from Azure and make a call to the APIController's method.

I have a stood up a console application as a client and test the above API and it works.

My question is:

What is it I have to do for me to have the ability to log whether my API has succeeded or failed in validating the bear-token that got passed in the header? How do I capture the access token that passed through the header.

Thank you

Upvotes: 0

Views: 639

Answers (1)

Vlad DX
Vlad DX

Reputation: 4730

I think you can add custom token handler and implement additional custom logic there.

Assuming that you have Web API OWIN application and use Microsoft.Owin.Security.ActiveDirectory NuGet package:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                // ...
                TokenHandler = new CustomTokenHandler(),
                // ...
            });
    }
}

// Custom token handler to apply custom logic to token validation
public class CustomTokenHandler : JwtSecurityTokenHandler
{
    public override ClaimsPrincipal ValidateToken(
        string token, TokenValidationParameters validationParameters,
        out SecurityToken validatedToken)
    {
        try
        {
            var claimsPrincipal = base.ValidateToken(token, validationParameters, out validatedToken);
            // You can do any logging of success here
            return claimsPrincipal;
        }
        catch (Exception e)
        {
            // You can do logging of failure here
            throw;
        }
    }
}



Upvotes: 2

Related Questions