1

我在自定义 owin 处理程序中看到此代码来执行 Oauth2。例如这里:https ://github.com/RockstarLabs/OwinOAuthProviders/blob/master/Owin.Security.Providers/Reddit/RedditAuthenticationHandler.cs

有人可以用简单的英语向我解释这两种方法在 oauth2 的上下文中的作用吗?它似乎与 CSRF 有关,但不确定如何。

4

1 回答 1

3

当重定向到“OAuth 2”合作伙伴时,必须通过某种方式将最终重定向回您自己的应用程序与您发送的原始重定向相关联。

Microsoft.OwinAuthenticationHandler实现此目的的方式:

  1. 生成随机字节的nonce并将其保留在浏览器 cookie ( GenerateCorrelationId)
  2. 加密此随机数和其他信息,您的工作是将其作为state查询字符串参数传递给合作伙伴(回想一下,合作伙伴的工作是在验证用户身份后将此值立即返回给您的应用程序)
  3. 通过解密state查询字符串参数并验证它与存储的 cookie 中的值匹配来验证 nonce ( ValidateCorrelationId)

这是来源

protected void GenerateCorrelationId(AuthenticationProperties properties)
{
    if (properties == null)
    {
        throw new ArgumentNullException("properties");
    }

    string correlationKey = Constants.CorrelationPrefix + 
                                BaseOptions.AuthenticationType;

    var nonceBytes = new byte[32];
    Random.GetBytes(nonceBytes);
    string correlationId = TextEncodings.Base64Url.Encode(nonceBytes);

    var cookieOptions = new CookieOptions
    {
        HttpOnly = true,
        Secure = Request.IsSecure
    };

    properties.Dictionary[correlationKey] = correlationId;

    Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
}

protected bool ValidateCorrelationId(AuthenticationProperties properties, 
                                     ILogger logger)
{
    if (properties == null)
    {
        throw new ArgumentNullException("properties");
    }

    string correlationKey = Constants.CorrelationPrefix + 
                                BaseOptions.AuthenticationType;

    string correlationCookie = Request.Cookies[correlationKey];
    if (string.IsNullOrWhiteSpace(correlationCookie))
    {
        logger.WriteWarning("{0} cookie not found.", correlationKey);
        return false;
    }

    var cookieOptions = new CookieOptions
    {
        HttpOnly = true,
        Secure = Request.IsSecure
    };

    Response.Cookies.Delete(correlationKey, cookieOptions);

    string correlationExtra;
    if (!properties.Dictionary.TryGetValue(
        correlationKey,
        out correlationExtra))
    {
        logger.WriteWarning("{0} state property not found.", correlationKey);
        return false;
    }

    properties.Dictionary.Remove(correlationKey);

    if (!string.Equals(correlationCookie, correlationExtra, StringComparison.Ordinal))
    {
        logger.WriteWarning("{0} correlation cookie and state property mismatch.", 
                                correlationKey);
        return false;
    }

    return true;
}
于 2016-08-26T14:24:40.130 回答