首页 文章

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

提问于
浏览
11

我创建了一个ASP.NET WEB API 2.2项目 . 我将基于Windows Identity Foundation的模板用于visual studio see it here中提供的个人帐户 .

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

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

因此,遵循LeastPrivilege的代码,我创建了一个继承自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);
    }

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

1 回答

  • 11

    我发现了罪魁祸首,在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;
        }
    }
    

相关问题