GenerateCorrelationId()和ValidateCorrelationId()有什么作用?

时间:2015-09-24 18:22:42

标签: owin owin-middleware

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

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

1 个答案:

答案 0 :(得分:3)

重定向到" OAuth 2"合作伙伴发生必须有一些将最终重定向与您发送的原始重定向关联回自己的应用程序。

Microsoft.Owin AuthenticationHandler实现此目的的方式:

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

    以下是the source

    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;
    }