问题 使用OWIN和ASP.NET WEB API的基本认证中间件


我创建了一个ASP.NET WEB API 2.2项目。我使用基于Windows Identity Foundation的模板为visual studio中提供的个人帐户 在这看到它

Web客户端(用angularJS编写)使用带有Web浏览器cookie的OAUTH实现来存储令牌和刷新令牌。我们受益于乐于助人 的UserManager 和 RoleManager 用于管理用户及其角色的类。 OAUTH和Web浏览器客户端一切正常。

但是,对于基于桌面的客户端的一些复古兼容性问题,我还需要支持基本身份验证。理想情况下,我想 [授权][授权(角色=“管理员”)] 等属性与OAUTH和基本身份验证方案一起使用。

因此,遵循代码 LeastPrivilege 我创建了一个OWIN BasicAuthenticationMiddleware 继承自 AuthenticationMiddleware。  我来到以下实现。为了 BasicAuthenticationMiddleWare 与Leastprivilege的代码相比,只有Handler发生了变化。实际上我们使用ClaimsIdentity而不是一系列 要求

 class BasicAuthenticationHandler: AuthenticationHandler<BasicAuthenticationOptions>
{
    private readonly string _challenge;

    public BasicAuthenticationHandler(BasicAuthenticationOptions options)
    {
        _challenge = "Basic realm=" + options.Realm;
    }

    protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
    {
        var authzValue = Request.Headers.Get("Authorization");
        if (string.IsNullOrEmpty(authzValue) || !authzValue.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
        {
            return null;
        }

        var token = authzValue.Substring("Basic ".Length).Trim();
        var claimsIdentity = await TryGetPrincipalFromBasicCredentials(token, Options.CredentialValidationFunction);

        if (claimsIdentity == null)
        {
            return null;
        }
        else
        {
            Request.User = new ClaimsPrincipal(claimsIdentity);
            return new AuthenticationTicket(claimsIdentity, new AuthenticationProperties());
        }
    }

    protected override Task ApplyResponseChallengeAsync()
    {
        if (Response.StatusCode == 401)
        {
            var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
            if (challenge != null)
            {
                Response.Headers.AppendValues("WWW-Authenticate", _challenge);
            }
        }

        return Task.FromResult<object>(null);
    }

    async Task<ClaimsIdentity> TryGetPrincipalFromBasicCredentials(string credentials,
        BasicAuthenticationMiddleware.CredentialValidationFunction validate)
    {
        string pair;
        try
        {
            pair = Encoding.UTF8.GetString(
                Convert.FromBase64String(credentials));
        }
        catch (FormatException)
        {
            return null;
        }
        catch (ArgumentException)
        {
            return null;
        }

        var ix = pair.IndexOf(':');
        if (ix == -1)
        {
            return null;
        }

        var username = pair.Substring(0, ix);
        var pw = pair.Substring(ix + 1);

        return await validate(username, pw);
    }

然后在Startup.Auth中我声明了以下委托用于验证身份验证(只检查用户是否存在以及密码是否正确并生成关联 ClaimsIdentity

 public void ConfigureAuth(IAppBuilder app)
    {
        app.CreatePerOwinContext(DbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        Func<string, string, Task<ClaimsIdentity>> validationCallback = (string userName, string password) =>
        {
            using (DbContext dbContext = new DbContext())
            using(UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(dbContext))
            using(ApplicationUserManager userManager = new ApplicationUserManager(userStore))
            {
                var user = userManager.FindByName(userName);
                if (user == null)
                {
                    return null;
                }
                bool ok = userManager.CheckPassword(user, password);
                if (!ok)
                {
                    return null;
                }
                ClaimsIdentity claimsIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                return Task.FromResult(claimsIdentity);
            }
        };

        var basicAuthOptions = new BasicAuthenticationOptions("KMailWebManager", new BasicAuthenticationMiddleware.CredentialValidationFunction(validationCallback));
        app.UseBasicAuthentication(basicAuthOptions);
        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            //If the AccessTokenExpireTimeSpan is changed, also change the ExpiresUtc in the RefreshTokenProvider.cs.
            AccessTokenExpireTimeSpan = TimeSpan.FromHours(2),
            AllowInsecureHttp = true,
            RefreshTokenProvider = new RefreshTokenProvider()
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
    }

但是,即使设置了 Request.User 在Handler的 AuthenticationAsyncCore 方法 [授权] 属性不能按预期工作:每次尝试使用基本身份验证方案时,都会对未经授权的错误401进行响应。 什么出错了?


12002
2017-07-21 21:22


起源



答案:


我找到了罪魁祸首,在WebApiConfig.cs文件中,“个人用户”模板插入了以下行。

//// Web API configuration and services
//// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

因此,我们还必须注册我们的 BasicAuthenticationMiddleware

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.Filters.Add(new HostAuthenticationFilter(BasicAuthenticationOptions.BasicAuthenticationType));

其中BasicAuthenticationType是传递给基础构造函数的常量字符串“Basic” BasicAuthenticationOptions

public class BasicAuthenticationOptions : AuthenticationOptions
{
    public const string BasicAuthenticationType = "Basic";

    public BasicAuthenticationMiddleware.CredentialValidationFunction CredentialValidationFunction { get; private set; }

    public BasicAuthenticationOptions( BasicAuthenticationMiddleware.CredentialValidationFunction validationFunction)
        : base(BasicAuthenticationType)
    {
        CredentialValidationFunction = validationFunction;
    }
}

11
2017-07-22 21:45