簡體   English   中英

具有OAuth和基本身份驗證的C#Web Api

[英]C# Web Api with OAuth and Basic authentication

我有一個使用OAuth配置的Asp.net Web API。 現在,我有一個新客戶端,他們不能使用Oauth,但想使用具有相同端點URL的基本身份驗證。

尚未找到任何方法來執行此操作。 在這方面的任何幫助表示贊賞。 提前致謝

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        if ((Thread.CurrentPrincipal.Identity.Name?.Length ?? 0) <= 0)
        {
            AuthenticationHeaderValue auth = actionContext.Request.Headers.Authorization;
            if (string.Compare(auth.Scheme, "Basic", StringComparison.OrdinalIgnoreCase) == 0)
            {
                string credentials = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter));
                int separatorIndex = credentials.IndexOf(':');
                if (separatorIndex >= 0)
                {
                    string userName = credentials.Substring(0, separatorIndex);
                    string password = credentials.Substring(separatorIndex + 1);
                    var userManager = new MembershipUserManager();
                    var user = userManager.FindAsync(userName, password).Result;
                    if (user != null)
                        Thread.CurrentPrincipal = actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(userName, "Basic"), System.Web.Security.Roles.Provider.GetRolesForUser(userName));
                }
            }
        }
        return base.IsAuthorized(actionContext);
    }
}

一旦設置了令牌auth(Oauth),就可以使用此代碼,這對兩種方法都適用:此屬性應在任何地方使用(放棄Authorize)[包含角色],並驗證Basic auth,而base.IsAuthorized(actionContext) ); 將驗證令牌方法(Oauth)。

MembershipUserManager是我創建的自定義類,以使其與Membership一起使用,我猜您將使用Identity User Manager。

暫無
暫無

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

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