-
Notifications
You must be signed in to change notification settings - Fork 25
WIP: OpenID based authentication for SMUI #62
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
Draft
epugh
wants to merge
5
commits into
master
Choose a base branch
from
spike_jwt_auth_lifecycle
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
a51e4e6
hacketity hack hack hack.... I don't know what i am doing....
33de780
Introduced a new JWTOpenIdAuthenticatedAction since this code flow is
0caaf76
Add JWKS call for token verification
mkr 628ada8
I couldn't get the resource_access key in the claim json to show up, …
039bc13
Read in these new props from docker env settings.
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 hidden or 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,78 @@ | ||
| package controllers | ||
|
|
||
| import javax.inject.Inject | ||
| import play.api.libs.json.Json | ||
| import play.api.mvc._ | ||
| import play.api.http.HttpErrorHandler | ||
| import play.api.{Configuration, Logging} | ||
| import scala.concurrent.{ExecutionContext, Future} | ||
| import scala.util.{Failure, Success, Try} | ||
| import scalaj.http.{Http, HttpOptions} | ||
| import pdi.jwt.{Jwt, JwtOptions, JwtAlgorithm, JwtClaim, JwtJson} | ||
|
|
||
|
|
||
|
|
||
| class OpenidController @Inject()(override val controllerComponents: ControllerComponents, errorHandler: HttpErrorHandler, appConfig: Configuration)(implicit ec: ExecutionContext) extends AbstractController(controllerComponents) with Logging { | ||
|
|
||
| private val JWT_COOKIE = getValueFromConfigWithFallback("smui.JWTOpenIdAuthenticatedAction.cookie.name", "jwt") | ||
|
|
||
| private def redirectToHomePage(): Future[Result] = { | ||
| Future { | ||
| Results.Redirect("http://localhost:9000/") | ||
| } | ||
| } | ||
|
|
||
| private def getValueFromConfigWithFallback(key: String, default: String): String = { | ||
| appConfig.getOptional[String](key) match { | ||
| case Some(value: String) => value | ||
| case None => | ||
| logger.warn(s":: No value for $key found. Setting pass to super-default.") | ||
| default | ||
| } | ||
| } | ||
|
|
||
| def callback() = Action { implicit request: Request[AnyContent] => | ||
| logger.warn("Here is the authorization code: " + request.getQueryString("code")) | ||
|
|
||
|
|
||
| val code: Option[String] = request getQueryString "code" | ||
| val upper = code map { _.trim } filter { _.length != 0 } | ||
|
|
||
|
|
||
| logger.warn("We now have a Authorization Code, and now we need to convert it to a Access Token.") | ||
|
|
||
| val result = Http("http://keycloak:9080/auth/realms/smui/protocol/openid-connect/token").postForm | ||
| .param("grant_type", "authorization_code") | ||
| .param("client_id", "smui") | ||
| .param("redirect_uri","http://localhost:9000/auth/openid/callback") | ||
| .param("code", upper getOrElse "") | ||
| .header("Content-Type", "application/x-www-form-urlencoded") | ||
| .header("Charset", "UTF-8") | ||
| .option(HttpOptions.readTimeout(10000)).asString | ||
|
|
||
| logger.warn(s"Result is $result" ) | ||
|
|
||
| val responseJson = Json.parse(result.body) | ||
|
|
||
| val accessToken : String = responseJson("access_token").as[String] | ||
|
|
||
| val decodedAccessToken = Jwt | ||
| .decodeRawAll( | ||
| accessToken, | ||
| JwtOptions(signature = false, expiration = false, notBefore = false) | ||
| ) | ||
|
|
||
|
|
||
| logger.warn("Decoded access token: " + decodedAccessToken) | ||
|
|
||
| // This should come from the decodedAccessToken, not from the responseJson ;-( | ||
| val scope : String = responseJson("scope").as[String] | ||
|
|
||
|
|
||
| logger.warn("Scope is " + scope) | ||
|
|
||
|
|
||
|
|
||
| Results.Redirect("http://localhost:9000/health").withCookies(Cookie(JWT_COOKIE, accessToken)) | ||
| } | ||
| } |
109 changes: 109 additions & 0 deletions
109
app/controllers/auth/JWTOpenIdAuthenticatedAction.scala
This file contains hidden or 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,109 @@ | ||
| package controllers.auth | ||
|
|
||
| import com.jayway.jsonpath.JsonPath | ||
| import net.minidev.json.JSONArray | ||
| import pdi.jwt.{Jwt, JwtOptions, JwtAlgorithm, JwtClaim, JwtJson} | ||
| import play.api.mvc._ | ||
| import pdi.jwt._ | ||
| import play.api.{Configuration, Logging} | ||
| import scalaj.http.{Http, HttpOptions} | ||
| import play.api.libs.json.Json | ||
| import java.util.Base64 | ||
| import scala.util.Success | ||
|
|
||
| import scala.concurrent.{ExecutionContext, Future} | ||
| import scala.util.{Failure, Success, Try} | ||
|
|
||
| class JWTOpenIdAuthenticatedAction(parser: BodyParsers.Default, appConfig: Configuration)(implicit ec: ExecutionContext) | ||
| extends ActionBuilderImpl(parser) with Logging { | ||
|
|
||
| logger.warn("In JWTOpenIdAuthenticatedAction") | ||
|
|
||
| private val JWT_LOGIN_URL = getValueFromConfigWithFallback("smui.JWTOpenIdAuthenticatedAction.login.url", "") | ||
| private val JWT_COOKIE = getValueFromConfigWithFallback("smui.JWTOpenIdAuthenticatedAction.cookie.name", "jwt") | ||
| private val JWT_AUTHORIZED_ROLES = getValueFromConfigWithFallback("smui.JWTOpenIdAuthenticatedAction.authorization.roles", "admin") | ||
|
|
||
| private lazy val authorizedRoles = JWT_AUTHORIZED_ROLES.replaceAll("\\s", "").split(",").toSeq | ||
|
|
||
| private def getValueFromConfigWithFallback(key: String, default: String): String = { | ||
| appConfig.getOptional[String](key) match { | ||
| case Some(value: String) => value | ||
| case None => | ||
| logger.warn(s":: No value for $key found. Setting pass to super-default.") | ||
| default | ||
| } | ||
| } | ||
|
|
||
|
|
||
|
|
||
| def decodeRawAll(jwt: String): Try[(String, String, String)] = { | ||
| Jwt | ||
| .decodeRawAll( | ||
| jwt, | ||
| JwtOptions(signature = false, expiration = false, notBefore = false) | ||
| ) | ||
| } | ||
|
|
||
| //private def isAuthenticated(jwt: String): Option[JwtClaim] = { | ||
| private def isAuthenticated(jwt: String): Option[Boolean] = { | ||
| logger.warn(s"\n Trying to deal with $jwt") | ||
|
|
||
|
|
||
| logger.warn("We should validate the token") | ||
|
|
||
| val result = for { | ||
| (header, claim, signature) <- | ||
| decodeRawAll(jwt) | ||
| } yield claim | ||
|
|
||
|
|
||
| logger.warn("claim: " + claim) | ||
|
|
||
|
|
||
|
|
||
| Some(true) | ||
| } | ||
|
|
||
| private def isAuthorized(token: String): Boolean = { | ||
| val rolesInToken = token.split(" ").toSeq | ||
| logger.warn("Here are the rolesinToken:" + rolesInToken) | ||
| rolesInToken.forall(authorizedRoles.contains) | ||
| } | ||
|
|
||
| private def redirectToLoginPage(): Future[Result] = { | ||
| Future { | ||
| Results.Redirect(JWT_LOGIN_URL) | ||
| } | ||
| } | ||
|
|
||
| private def getJwtCookie[A](request: Request[A]): Option[Cookie] = { | ||
| request.cookies.get(JWT_COOKIE) | ||
| } | ||
|
|
||
|
|
||
|
|
||
| override def invokeBlock[A](request: Request[A], block: Request[A] => Future[Result]): Future[Result] = { | ||
|
|
||
| logger.warn(s":: invokeBlock :: request.path = ${request.path}") | ||
|
|
||
| if (request.path == "/auth/openid/callback"){ | ||
| // https://www.appsdeveloperblog.com/keycloak-authorization-code-grant-example/ | ||
| logger.warn("We got a callback!!!!"); | ||
|
|
||
| } | ||
| getJwtCookie(request) match { | ||
| case Some(cookie) => | ||
| isAuthenticated(cookie.value) match { | ||
| case Some(token) if isAuthorized("smui:searchandizder") => block(request) | ||
| case _ => redirectToLoginPage() | ||
| } | ||
| case None => redirectToLoginPage() | ||
| } | ||
|
|
||
| //if (isAuthorized("smui:searchandizer")) { | ||
| // block(request) | ||
| //} else { | ||
| // redirectToLoginPage | ||
| //} | ||
| } | ||
| } | ||
This file contains hidden or 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 hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.