【问题标题】:C# Web Api with OAuth and Basic authentication具有 OAuth 和基本身份验证的 C# Web Api
【发布时间】:2018-09-02 06:51:32
【问题描述】:

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

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

【问题讨论】:

  • 感谢您的回复。这不是重复的。检查了链接。这里的问题是如何根据请求使用 OAuth/Basic 身份验证。
  • 我不认为2可以集成。我能想到的唯一可行的方法是拥有一个需要基本身份验证的网页,然后可以获取承载令牌并使用承载令牌向主应用程序进行身份验证。
  • @MoD 任何可以提供帮助的示例代码

标签: c# authentication asp.net-web-api oauth basic-authentication


【解决方案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);
    }
}

一旦设置了令牌身份验证 (Oauth),就可以使用此代码,这对两者都适用:此属性应在任何地方使用(放弃授权)[包含角色],并将验证基本身份验证,而基础身份验证。 IsAuthorized(actionContext);将验证令牌方法(Oauth)。

MembershipUserManager 是我创建的一个自定义类,用于与 Membership 一起工作,我猜你会使用 Identity User Manager。

【讨论】:

  • 谢谢@Riste Golaboski。我会试试这个并在这里更新。
猜你喜欢
  • 2015-09-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 2014-05-02
  • 1970-01-01
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多