【问题标题】:WebApi OWIN same token valid for two different instances of serviceWebApi OWIN 相同的令牌对两个不同的服务实例有效
【发布时间】:2018-12-31 03:43:55
【问题描述】:

我已经使用 OWIN 库创建了 WebApi 自托管服务。一切都很好,除了一些身份验证问题。我已经在服务器上启动了两个服务实例,结果表明从一个服务获得的令牌对第二个服务有效!据我所知,OWIN 使用一些保护密钥验证了令牌。问题是:

  1. 如何使其他服务实例的密钥无效?我曾尝试使用 Generate-MachineKey 生成自定义密钥,但结果是一样的。
  2. OWIN 使用的保护密钥是什么?它存储在某个地方吗?
  3. 此密钥对于不同的应用程序是否有所不同?

设置:

var oAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(accessTokenExipreMinutes),
    Provider = new AuthorizationServerProvider(),
    AllowInsecureHttp = allowInsecureHttp
};

appBuilder.UseOAuthBearerTokens(oAuthOptions);  

授权服务器提供者:

class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.TryGetFormCredentials(out string clientId, out string clientSecret);

        var result = Validate(clientId, clientSecret);
        if (result)
        {
            context.Validated(clientId);
            return;
        }

        context.Rejected();
    }

    public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        try
        {
            ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            var props = new AuthenticationProperties();
            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
        }
        catch (Exception ex)
        {
            context.Rejected();
        }

        return Task.FromResult(true);
    }
}

【问题讨论】:

    标签: c# oauth oauth-2.0 asp.net-web-api2 owin


    【解决方案1】:

    OAuthAuthorizationServerOptions 中有一个名为AccessTokenFormat 的属性,它将AuthenticationTicket 转换为byte[],反之亦然。此选项加密令牌。您可以为不同的应用程序实例使用不同的密钥设置此选项,这样它们就无法读取彼此的令牌。

    这就是你设置AccessTokenFormat的方式

    using Microsoft.Owin.Security.DataProtection; 
    using Microsoft.Owin.Security.DataHandler;
    
    IDataProtector dataProtecter = app.CreateDataProtector("YOUR_KEY");
    var ticketDataFormat = new TicketDataFormat(dataProtecter);
    new OAuthAuthorizationServerOptions
    {
        TicketDataFormat = ticketDataFormat
    };
    

    Owin 的默认设置是使用您的 Machine Key 来创建 TicketDataFormat,因此您也可以在 web.config 中为您的实例设置不同的 Machine Key。

    【讨论】:

    • 谢谢!效果很好!附加信息 - 上面的代码需要两个命名空间:Microsoft.Owin.Security.DataProtection; Microsoft.Owin.Security.DataHandler;
    • 我无法使用机器密钥,因为它是自托管应用程序
    猜你喜欢
    • 2018-03-03
    • 2018-01-04
    • 1970-01-01
    • 2010-11-05
    • 2020-11-21
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多