OWIN安全性 - 如何在保持身份验证承载令牌的同时在cookie中返回刷新令牌

Dan*_*ski 5 c# oauth-2.0 asp.net-web-api owin asp.net-identity

我在基于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());
}
Run Code Online (Sandbox Code Playgroud)

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

有没有办法可以在auth配置中实现这一点,这是正确的方法吗?如果我能提供帮助,我不想走错方向.

Wil*_*lWa 2

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

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

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

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

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

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

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