【问题标题】:OWIN Security - How to return a refresh token in a cookie while maintaining authentication bearer tokensOWIN Security - 如何在 cookie 中返回刷新令牌,同时维护身份验证承载令牌
【发布时间】:2015-07-25 03:05:48
【问题描述】:

我正在基于 Web API 2 模板的 Web 服务中设置刷新令牌。我们自己的网站以及外部客户都将使用它。

经过一段时间的研究,保护刷新令牌免受 XSS 攻击的一般建议是将标识符存储在加密的 cookie 中。我知道我可以通过使用 UseCookieAuthentication 方法而不是 UseOAuthBearerAuthentication 来返回 cookie 中的身份验证和刷新令牌,但是当我与外部客户端打交道时会导致复杂性。

我目前用于设置配置的代码是:

public void ConfigureAuth(IAppBuilder app)
{
    var applicationProvider = new ApplicationOAuthProvider();

    var applicationRefreshProvider = new ApplicationRefreshTokenProvider();

    var oAuthServerOptions = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,

        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),

        Provider = applicationProvider,
        RefreshTokenProvider = applicationRefreshProvider
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(oAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}

我可以实现的解决方法是向资源服务器上的控制器添加一个方法,然后为基于 javascript 的客户端执行转换步骤,但这对我来说不太有意义。

有没有办法可以在身份验证配置中完成此操作,这是正确的方法吗?如果我能帮上忙,我不想走错方向。

【问题讨论】:

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


    【解决方案1】:

    我也一直在研究这个问题,我只是在试验,我还没有最终确定解决方案。但是,我发现在我的 refreshTokenProvider 中,在 CreateAsync 方法中,而不是 context.SetToken 我可以这样做:

    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
      // actual logic that retrieves refresh token...
      context.Response.Cookies.Append("refresh_token", refreshToken.ToString());
    }
    

    这将在响应中设置一个 cookie,而不是像预期的那样将刷新令牌添加到 JSON 响应正文。我的计划是执行此操作或使用 SetToken,具体取决于请求刷新令牌的客户端。

    然后,在 ReceiveAsync 方法中,我有:

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
      var refreshToken = context.Request.Cookies["request_token"];
      // actual logic that verifies refresh token, etc. 
    }
    

    到目前为止,我发现的唯一警告是发送 grant_type=refresh_token 请求时创建的 AuthenticationTokenReceiveContext 构造函数不允许空令牌,因此如果我将 any 字符串作为 refresh_token 传递会正常工作的。

    重复一遍,我还没有完全充实它。我需要弄清楚如何减轻 CSRF 攻击并显然加密 cookie,将其标记为仅 http 等。我确信这些都不是不可克服的。但我希望这可能对其他人有所帮助并可能引发讨论,因为老实说,我也不知道我是否“正确”地这样做了。不过,它有效,我的目标是提出一个解决方案:http://jeremymarc.github.io/2014/08/14/oauth2-with-angular-the-right-way/

    【讨论】:

    • 这几乎就是我最终采用的方法。 cookie 代码使用new CookieOptions { Secure = context.OwinContext.Request.IsSecure, Expires = token.ExpiresUtc, HttpOnly = true, Path = context.Request.Uri.LocalPath } 等安全选项进行了扩展,但总体方法是相同的。我真的希望刷新令牌返回与基本实现中的身份验证令牌正确分离,但希望它出现在后面的迭代中。
    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多