-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add AuthorisedAction #13
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
2b410af
Add AuthorisedAction
kelvin-chappell a56f39a
Merge branch 'main' into kc/auth
kelvin-chappell 3c943e1
Test for an invalid access token
kelvin-chappell 9e9f707
Merge branch 'main' into kc/auth
kelvin-chappell 263de1f
Merge branch 'main' into kc/auth
kelvin-chappell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package auth | ||
|
||
import com.gu.identity.auth.AccessScope | ||
|
||
object AccessScopes { | ||
|
||
case object UserReadSelfSecure extends AccessScope { | ||
val name = "guardian.identity-api.user.read.self.secure" | ||
} | ||
} |
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,40 @@ | ||
package auth | ||
|
||
import com.gu.identity.auth.* | ||
import play.api.mvc.* | ||
import play.api.mvc.Results.* | ||
|
||
import scala.concurrent.{ExecutionContext, Future} | ||
|
||
/** An action that requires a valid access token with the given required access scopes. If the token is valid, the | ||
* request is passed to the next action in the chain. | ||
* | ||
* If the request doesn't have an Authorization header or the bearer token in the header isn't a valid access token, | ||
* the action returns a 401 Unauthorized response. If the token is valid but doesn't have the required scopes, the | ||
* action returns a 403 Forbidden response. | ||
*/ | ||
class AuthorisedAction(oktaAuthService: OktaAuthService, requiredScopes: List[AccessScope])(implicit | ||
val executionContext: ExecutionContext | ||
) extends ActionBuilder[RequestWithClaims, AnyContent] | ||
with ActionRefiner[Request, RequestWithClaims] { | ||
|
||
def parser: BodyParser[AnyContent] = BodyParsers.utils.ignore(AnyContentAsEmpty: AnyContent) | ||
|
||
protected def refine[A](request: Request[A]): Future[Either[Result, RequestWithClaims[A]]] = { | ||
Helpers.fetchBearerTokenFromAuthHeader(request.headers.get) match { | ||
case Left(_) => Future.successful(Left(Unauthorized("Request has no Authorization header"))) | ||
case Right(token) => | ||
oktaAuthService | ||
.validateAccessToken(AccessToken(token), requiredScopes) | ||
.redeem( | ||
{ | ||
case OktaValidationException(err: ValidationError) => | ||
Left(new Status(err.suggestedHttpResponseCode)(err.message)) | ||
case err => Left(InternalServerError(err.getMessage)) | ||
}, | ||
claims => Right(RequestWithClaims(claims, request)) | ||
) | ||
.unsafeToFuture() | ||
} | ||
} | ||
} |
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,6 @@ | ||
package auth | ||
|
||
import com.gu.identity.auth.DefaultAccessClaims | ||
import play.api.mvc.{Request, WrappedRequest} | ||
|
||
class RequestWithClaims[A](val claims: DefaultAccessClaims, request: Request[A]) extends WrappedRequest[A](request) |
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,15 @@ | ||
package controllers | ||
|
||
import auth.AccessScopes.UserReadSelfSecure | ||
import auth.AuthorisedAction | ||
import com.gu.identity.auth.AccessScope | ||
import play.api.* | ||
import play.api.mvc.* | ||
|
||
class UserController( | ||
val controllerComponents: ControllerComponents, | ||
authorisedAction: List[AccessScope] => AuthorisedAction | ||
) extends BaseController { | ||
|
||
def me(): Action[AnyContent] = authorisedAction(List(UserReadSelfSecure))(NotImplemented("TODO: implement me")) | ||
} |
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 |
---|---|---|
@@ -1,21 +1,31 @@ | ||
package load | ||
|
||
import auth.AuthorisedAction | ||
import com.gu.identity.auth.{OktaAudience, OktaAuthService, OktaIssuerUrl, OktaTokenValidationConfig} | ||
import controllers.{HealthCheckController, UserController} | ||
import logging.RequestLoggingFilter | ||
import play.api.ApplicationLoader.Context | ||
import play.api.BuiltInComponentsFromContext | ||
import play.api.mvc.EssentialFilter | ||
import play.api.{BuiltInComponentsFromContext, Configuration} | ||
import play.filters.HttpFiltersComponents | ||
import router.Routes | ||
import software.amazon.awssdk.regions.Region | ||
import software.amazon.awssdk.services.ssm.SsmClient | ||
import software.amazon.awssdk.services.ssm.model.GetParameterRequest | ||
|
||
import scala.util.Using | ||
|
||
class AppComponents(context: Context) extends BuiltInComponentsFromContext(context) with HttpFiltersComponents { | ||
|
||
override def httpFilters: Seq[EssentialFilter] = super.httpFilters :+ new RequestLoggingFilter(materializer) | ||
|
||
lazy val healthCheckController = new controllers.HealthCheckController(controllerComponents) | ||
lazy val router: Routes = new Routes(httpErrorHandler, healthCheckController) | ||
private lazy val authService = OktaAuthService( | ||
OktaTokenValidationConfig( | ||
issuerUrl = OktaIssuerUrl(context.initialConfiguration.get[String]("idProvider.issuer")), | ||
audience = Some(OktaAudience(context.initialConfiguration.get[String]("idProvider.audience"))), | ||
clientId = None, | ||
) | ||
) | ||
|
||
private lazy val authorisedAction = new AuthorisedAction(authService, _) | ||
|
||
private lazy val healthCheckController = new HealthCheckController(controllerComponents) | ||
private lazy val userController = new UserController(controllerComponents, authorisedAction) | ||
|
||
lazy val router: Routes = new Routes(httpErrorHandler, healthCheckController, userController) | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,6 @@ | ||
include "application.conf" | ||
|
||
idProvider { | ||
issuer = "https://profile.code.dev-theguardian.com/oauth2/aus3v9gla95Toj0EE0x7" | ||
audience = "https://profile.code.dev-theguardian.com/" | ||
} |
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 |
---|---|---|
@@ -1 +1,6 @@ | ||
include "application.conf" | ||
|
||
idProvider { | ||
issuer = "https://profile.code.dev-theguardian.com/oauth2/aus3v9gla95Toj0EE0x7" | ||
audience = "https://profile.code.dev-theguardian.com/" | ||
} |
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 |
---|---|---|
@@ -1 +1,6 @@ | ||
include "application.conf" | ||
|
||
idProvider { | ||
issuer = "https://profile.theguardian.com/oauth2/aus3xgj525jYQRowl417" | ||
audience = "https://profile.theguardian.com/" | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
package auth | ||
|
||
import cats.effect.IO | ||
import com.gu.identity.auth.* | ||
import org.mockito.Mockito.when | ||
import org.scalatest.matchers.should.Matchers.shouldBe | ||
import org.scalatestplus.mockito.MockitoSugar.mock | ||
import org.scalatestplus.play.* | ||
import play.api.mvc.* | ||
import play.api.mvc.Results.* | ||
import play.api.test.* | ||
import play.api.test.Helpers.* | ||
|
||
import scala.concurrent.ExecutionContext.Implicits.global | ||
|
||
class AuthorisedActionSpec extends PlaySpec { | ||
|
||
"refine" should { | ||
|
||
val requiredScopes = List(new AccessScope { | ||
override def name: String = "requiredScope" | ||
}) | ||
|
||
"return 401 when there is no Authorization header" in { | ||
val authService = mock[OktaAuthService] | ||
val action = new AuthorisedAction(authService, requiredScopes) | ||
val request = FakeRequest(GET, "/") | ||
val result = action(Ok)(request) | ||
status(result) shouldBe UNAUTHORIZED | ||
contentType(result) shouldBe Some("text/plain") | ||
contentAsString(result) shouldBe "Request has no Authorization header" | ||
} | ||
|
||
"return 401 when the token is invalid" in { | ||
val authService = mock[OktaAuthService] | ||
when(authService.validateAccessToken(AccessToken("invalidToken"), requiredScopes)) | ||
.thenReturn(IO.raiseError(OktaValidationException(InvalidOrExpiredToken))) | ||
val action = new AuthorisedAction(authService, requiredScopes) | ||
val request = FakeRequest(GET, "/").withHeaders("Authorization" -> "Bearer invalidToken") | ||
val result = action(Ok)(request) | ||
status(result) shouldBe UNAUTHORIZED | ||
contentType(result) shouldBe Some("text/plain") | ||
contentAsString(result) shouldBe "Token is invalid or expired" | ||
} | ||
|
||
"return 403 when the token is valid but doesn't have the required scopes" in { | ||
val authService = mock[OktaAuthService] | ||
when(authService.validateAccessToken(AccessToken("validToken"), requiredScopes)) | ||
.thenReturn(IO.raiseError(OktaValidationException(MissingRequiredScope(requiredScopes)))) | ||
val action = new AuthorisedAction(authService, requiredScopes) | ||
val request = FakeRequest(GET, "/").withHeaders("Authorization" -> "Bearer validToken") | ||
val result = action(Ok)(request) | ||
status(result) shouldBe FORBIDDEN | ||
contentType(result) shouldBe Some("text/plain") | ||
contentAsString(result) shouldBe "Token is missing required scope(s): requiredScope" | ||
} | ||
|
||
"return 200 when the token is valid and has the required scopes" in { | ||
val requiredScopes = List(new AccessScope { | ||
override def name: String = "requiredScope" | ||
}) | ||
val authService = mock[OktaAuthService] | ||
when(authService.validateAccessToken(AccessToken("validToken"), requiredScopes)) | ||
.thenReturn( | ||
IO.pure(DefaultAccessClaims(primaryEmailAddress = "a@b.com", identityId = "I43", username = None)) | ||
) | ||
val action = new AuthorisedAction(authService, requiredScopes) | ||
val request = FakeRequest(GET, "/").withHeaders("Authorization" -> "Bearer validToken") | ||
val result = action(Ok)(request) | ||
status(result) shouldBe OK | ||
} | ||
} | ||
} |
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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
are we missing the case where the token is present but invalid ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Added in 3c943e1