我必须验证来自OAuth签名的服务器的请求调用。这个请求调用是对我的服务器进行的,我需要验证该请求是从该服务器发出的。我有oauth消费者的密钥和消费者的秘密。我一直在研究路标和泽西图书馆API的签名验证。他们帮不了多少忙。调用是从一个特定的服务器(使用两条腿的OAuth 1.0)向我的servlet发出的。请建议一个更简单的库或示例来进行OAuth验证。
发布于 2015-11-26 17:13:45
在使用Scala中的Play框架编写web服务时,我遇到了同样的问题,为了解决这个问题,我不得不使用Java库编写代码,所以即使我的代码片段在Scala中,我也认为它会有所帮助。这个答案可能来得有点晚,但希望有人会发现它有用。
在我的示例中,外部服务正在调用我的REST端点,同时在授权头中提供不同的oauth参数。为了验证作为这些参数的一部分而提供的oauth_signature,我必须从报头中提取nonce和时间戳参数,并根据它们再加上其他一些参数(包括oauth密钥和机密以及原始请求uri )计算一个签名。
这段代码在scala中,但我认为您可以从中推断出该做什么。它还在使用Java OAuthSignatureCalculator,因此在java中直接编写代码可能更容易。
private def getProtocolFromRequest[T](request: Request[T]): String = {
// To handle the case where a SSL offloading is involved
request.headers.get(HeaderNames.X_FORWARDED_PROTO) match {
case Some(forwardedProto: String) => forwardedProto
case _ => if(request.secure) "https" else "http"
}
}
def isOAuthSignatureValid[T](request: Request[T]): Boolean = {
request.headers.get(com.ning.http.client.oauth.OAuthSignatureCalculator.HEADER_AUTHORIZATION) match {
case Some(authorizationHeaders) =>
val AuthRegex = ".*oauth_nonce=\"([^\"]*)\".*oauth_signature=\"([^\"]*)\".*oauth_timestamp=\"([^\"]*)\".*".r
authorizationHeaders match {
case AuthRegex(nonce: String, providedSignature: String, timestamp: String) =>
val signatureCalculator = new OAuthSignatureCalculator(new com.ning.http.client.oauth.ConsumerKey(oauthKey, oauthSecret), new com.ning.http.client.oauth.RequestToken(null, ""))
val params = request.queryString.map(query => new Param(query._1, query._2.head)).toSeq
val protocol = getProtocolFromRequest(request)
val url = s"$protocol://${request.host}${request.path}"
val expectedSignature = signatureCalculator.calculateSignature(
request.method,
Uri.create(url),
timestamp.toInt,
nonce,
new util.ArrayList(),
scala.collection.JavaConversions.seqAsJavaList(params)
)
expectedSignature.equals(URLDecoder.decode(providedSignature, "UTF-8"))
case _ => false
}
case _ => false
}
}流动情况如下:
希望这能帮到别人
https://stackoverflow.com/questions/28278262
复制相似问题