-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Pass redirect url through OAuth state
TokenResponse is a better name for that endpoint More wip More wip WIP
- Loading branch information
Showing
9 changed files
with
270 additions
and
96 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 71 additions & 0 deletions
71
module/src/main/scala/com/gu/googleauth/GoogleOAuthService.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package com.gu.googleauth | ||
|
||
import play.api.libs.json.JsValue | ||
import play.api.libs.ws.{WSClient, WSResponse} | ||
|
||
import scala.concurrent.{ExecutionContext, Future} | ||
import scala.language.postfixOps | ||
|
||
case class OAuthConfig( | ||
clientId: String, | ||
clientSecret: String, | ||
redirectUrl: String | ||
) | ||
|
||
class GoogleOAuthService(config: OAuthConfig, dd: DiscoveryDocument)(implicit context: ExecutionContext, ws: WSClient) { | ||
|
||
def googleResponse[T](r: WSResponse)(block: JsValue => T): T = { | ||
r.status match { | ||
case errorCode if errorCode >= 400 => | ||
// try to get error if google sent us an error doc | ||
val error = (r.json \ "error").asOpt[Error] | ||
error.map { e => | ||
throw new GoogleAuthException(s"Error when calling Google: ${e.message}") | ||
}.getOrElse { | ||
throw new GoogleAuthException(s"Unknown error when calling Google [status=$errorCode, body=${r.body}]") | ||
} | ||
case normal => block(r.json) | ||
} | ||
} | ||
|
||
// https://developers.google.com/identity/protocols/OpenIDConnect#exchangecode | ||
def exchangeCodeForToken(code: String): Future[TokenResponse] = { | ||
val requestBody = Map[String, Seq[String]]( | ||
"code" -> Seq(code), | ||
"client_id" -> Seq(config.clientId), | ||
"client_secret" -> Seq(config.clientSecret), | ||
"redirect_uri" -> Seq(config.redirectUrl), | ||
"grant_type" -> Seq("authorization_code") | ||
) | ||
|
||
for { | ||
response <- ws.url(dd.token_endpoint).post(requestBody) | ||
} yield googleResponse(response)(TokenResponse.fromJson) | ||
} | ||
|
||
// https://developers.google.com/identity/protocols/OpenIDConnect#obtaininguserprofileinformation | ||
def fetchUserInfo(tr: TokenResponse): Future[UserInfo] = for { | ||
response <- ws.url(dd.userinfo_endpoint).withHttpHeaders("Authorization" -> s"Bearer ${tr.access_token}").get() | ||
} yield googleResponse(response)(UserInfo.fromJson) | ||
|
||
|
||
def fetchUserIdentityForCode(code: String): Future[UserIdentity] = { | ||
val requiredDomain: Option[String]= ??? | ||
for { | ||
tokenResponse <- exchangeCodeForToken(code) | ||
jwt = tokenResponse.jwt | ||
// requiredDomain foreach { domain => | ||
// if (!jwt.claims.email.split("@").lastOption.contains(domain)) | ||
// throw new GoogleAuthException("Configured Google domain does not match") | ||
// } | ||
userInfo <- jwt.claimsJson.validate[UserInfo].asOpt.map(Future.successful).getOrElse(fetchUserInfo(tokenResponse)) | ||
} yield UserIdentity( | ||
jwt.claims.sub, | ||
jwt.claims.email, | ||
userInfo.given_name, | ||
userInfo.family_name, | ||
jwt.claims.exp, | ||
userInfo.picture | ||
) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
package com.gu.googleauth | ||
|
||
import java.nio.charset.StandardCharsets.UTF_8 | ||
import java.time.Clock | ||
import java.util.{Base64, Date} | ||
|
||
import com.gu.googleauth.Destination.Encryption._ | ||
import com.gu.googleauth.GoogleAuthFilters.LOGIN_ORIGIN_KEY | ||
import com.gu.googleauth.OAuthStateSecurityConfig.SessionIdJWTClaimPropertyName | ||
import io.jsonwebtoken.{Claims, Jws, Jwts, SignatureAlgorithm} | ||
import org.jose4j.jwa.AlgorithmConstraints | ||
import org.jose4j.jwa.AlgorithmConstraints.ConstraintType.WHITELIST | ||
import org.jose4j.jwe.ContentEncryptionAlgorithmIdentifiers.AES_128_CBC_HMAC_SHA_256 | ||
import org.jose4j.jwe.JsonWebEncryption | ||
import org.jose4j.jwe.KeyManagementAlgorithmIdentifiers.A128KW | ||
import org.jose4j.keys.AesKey | ||
import play.api.mvc.Session | ||
|
||
import scala.util.{Failure, Success, Try} | ||
|
||
|
||
case class OAuthState(sessionId: String, encryptedReturnUrl: String) { | ||
def checkSessionIdMatches(session: Session):Try[Unit] = | ||
if (session(SessionId.KeyName).contains(sessionId)) Success(()) else | ||
Failure(throw new IllegalArgumentException(s"Session id does not match")) | ||
} | ||
|
||
object Destination { | ||
val KeyName = "destinationUrl" | ||
|
||
object Encryption { | ||
val KeyManagementAlgorithm = A128KW | ||
val ContentEncryptionAlgorithm = AES_128_CBC_HMAC_SHA_256 | ||
} | ||
|
||
case class Encryption(secret: String) { | ||
|
||
val key = new AesKey(secret.getBytes(UTF_8)) | ||
|
||
def encrypt(destinationUrl: String): String = { | ||
var jwe = new JsonWebEncryption | ||
jwe.setPayload(destinationUrl) | ||
jwe.setAlgorithmHeaderValue(KeyManagementAlgorithm) | ||
jwe.setEncryptionMethodHeaderParameter(ContentEncryptionAlgorithm) | ||
jwe.setKey(key) | ||
jwe.getCompactSerialization | ||
} | ||
|
||
def decrypt(encryptedDestinationUrl: String): String = { | ||
val jwe = new JsonWebEncryption | ||
jwe.setAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, KeyManagementAlgorithm)) | ||
jwe.setContentEncryptionAlgorithmConstraints(new AlgorithmConstraints(WHITELIST, ContentEncryptionAlgorithm)) | ||
jwe.setKey(key) | ||
jwe.setCompactSerialization(encryptedDestinationUrl) | ||
jwe.getPayload | ||
} | ||
} | ||
} | ||
|
||
object OAuthState { | ||
|
||
case class Encoding(secret: String, signatureAlgorithm: SignatureAlgorithm) { | ||
|
||
private val base64EncodedSecret: String = | ||
Base64.getEncoder.encodeToString(secret.getBytes(UTF_8)) | ||
|
||
def checkChoiceOfSigningAlgorithm(claims: Jws[Claims]): Try[Unit] = | ||
if (claims.getHeader.getAlgorithm == signatureAlgorithm.getValue) Success(()) else | ||
Failure(throw new IllegalArgumentException(s"the anti forgery token is not signed with $signatureAlgorithm")) | ||
|
||
def extractOAuthStateFrom(state: String): Try[OAuthState] = for { | ||
jwtClaims <- Try(Jwts.parser().setSigningKey(base64EncodedSecret).parseClaimsJws(state)) | ||
_ <- checkChoiceOfSigningAlgorithm(jwtClaims) | ||
} yield OAuthState( | ||
sessionId = jwtClaims.getBody.get(SessionIdJWTClaimPropertyName, classOf[String]), | ||
encryptedReturnUrl = jwtClaims.getBody.get(LOGIN_ORIGIN_KEY, classOf[String]) | ||
) | ||
|
||
def stringify(oAuthState: OAuthState)(implicit clock: Clock = Clock.systemUTC) : String = Jwts.builder() | ||
.setExpiration(Date.from(clock.instant().plusSeconds(60))) | ||
.claim(SessionIdJWTClaimPropertyName, oAuthState.sessionId) | ||
.claim(LOGIN_ORIGIN_KEY, oAuthState.encryptedReturnUrl) | ||
.signWith(signatureAlgorithm, base64EncodedSecret) | ||
.compact() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
package com.gu.googleauth | ||
|
||
import java.math.BigInteger | ||
import java.security.SecureRandom | ||
|
||
import play.api.mvc.{RequestHeader, Result} | ||
|
||
import scala.concurrent.{ExecutionContext, Future} | ||
|
||
object SessionId { | ||
val KeyName = "play-googleauth-session-id" | ||
|
||
private val random = new SecureRandom() | ||
def generateSessionId() = new BigInteger(130, random).toString(32) | ||
|
||
def ensureUserHasSessionId(t: String => Future[Result])(implicit request: RequestHeader, ec: ExecutionContext):Future[Result] = { | ||
val sessionId = request.session.get(KeyName).getOrElse(generateSessionId()) | ||
|
||
t(sessionId).map(_.addingToSession(KeyName -> sessionId)) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.