簡體   English   中英

用於調試的OAuth承載令牌日志

[英]OAuth bearer-token log for debug

我有一個.net Rest API,並且我正在使用Azure ADD for OAuth。

Startup.cs我有以下內容:

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

Startup.Auth.cs我具有以下功能:(顯然,我已在AppSettings中添加了我的Azure應用信息)

// 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"]
                }
            });
    }

並且,在我的API Controller.cs中,添加了[Authorize]屬性。

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

客戶端應用程序將從Azure獲得一個空頭令牌並調用APIController的方法。

我有一個作為客戶端的控制台應用程序,並測試了上述API,它可以工作。

我的問題是:

為了能夠記錄我的API驗證在標頭中傳遞的空頭令牌是成功還是失敗,我該怎么辦? 如何捕獲通過標頭傳遞的訪問令牌。

謝謝

我認為您可以在其中添加自定義令牌處理程序並實現其他自定義邏輯。

假設您具有Web API OWIN應用程序並使用Microsoft.Owin.Security.ActiveDirectory NuGet包:

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



暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM