具有OAuth和基本身份验证的C#Web Api

问题描述 投票:0回答:1

我有一个Asp.net web api,它配置了OAuth。现在我有新的客户端不能使用Oauth但想要使用相同端点URL的基本身份验证。

还没有找到任何方法来做到这一点。对此有任何帮助表示赞赏。提前致谢

c# authentication asp.net-web-api oauth basic-authentication
1个回答
1
投票
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)后使用此代码,这对两者都有效:此属性应在任何地方使用(抛弃授权)[包含角色]并验证Basic身份验证,而base.IsAuthorized(actionContext) );将验证令牌方法(Oauth)。

MembershipUserManager是我创建的自定义类,用于使用Membership,我猜你会使用Identity User Manager。

© www.soinside.com 2019 - 2024. All rights reserved.