使用OWIN和ASP.NET WEB API的基本身份验证中间件

12
我创建了一个ASP.NET WEB API 2.2项目,使用了基于Windows身份验证基础的模板来进行个人账户设置,该模板在Visual Studio中可用(在此处查看)
Web客户端(使用AngularJS编写)使用OAUTH实现,并使用Web浏览器cookie存储令牌和刷新令牌。我们可以使用有用的和类来管理用户及其角色。 OAUTH和Web浏览器客户端一切正常。
然而,由于需要与基于桌面的客户端进行兼容,我还需要支持基本身份验证。理想情况下,我希望、等属性能够同时适用于OAUTH和基本身份验证方案。
因此,按照最小特权的代码,我创建了一个继承自AuthenticationMiddleware的OWIN BasicAuthenticationMiddleware。 我得到了以下实现。对于BasicAuthenticationMiddleWare,与Leastprivilege的代码相比,只有Handler发生了变化。实际上,我们使用ClaimsIdentity而不是一系列的Claim
 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);
    }

然而,即使在处理程序的AuthenticationAsyncCore方法中设置了Request.User[Authorize]属性也无法按预期工作:每次尝试使用基本身份验证方案时都会响应错误401未经授权。 有什么想法是出了什么问题吗?
1个回答

13
我找出了罪魁祸首,在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是传递给BasicAuthenticationOptions的基本构造函数的常量字符串"Basic"

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接