Akka http 401 on not authenticated endpoint - scala

I have the following routes definition
private val routes: Route =
concat(
pathEnd {
get {
handleErrorsAndReport("list_foos") {
}
}
},
path(Segment) { fooId =>
get {
handleErrorsAndReport("get_foo") {
rejectEmptyResponse(
complete(service.do(fooId))
)
}
}
},
pathEnd {
authenticateBasic(
realm = "Secure scope",
scopesAuthenticator
) { scopes =>
post {
handleErrorsAndReport("create_foo") {
}
}
}
},
path(Segment) { fooId =>
authenticateBasic(
realm = "Secure scopes",
scopesAuthenticator
) { scopes =>
concat(
put {
handleErrorsAndReport("update_foo") {
}
},
delete {
handleErrorsAndReport("delete_foo") {
}
}
)
}
}
)
I am trying to consume the get_foo endpoint. I have created a unit test for that and it looks like this
"allow get operation on foo without authentication present" in {
Get("/foos/{some_id}") ~> routes ~> check {
status shouldBe StatusCodes.NotFound
}
}
While debugging the test I can see that the route is correctly identified and I can access the code inside the route. The service code inside the get_foo route produces a None and complete(None) creates a rejection since it's an empty response and I have the rejectEmptyResponse directive. So I would expect that I would get a 404 response based on the handleErrorsAndReport directive that I have defined. The error handler looks like this
private def handleErrorsAndReport(endpoint: String): Directive0 = extractRequestContext.flatMap { ctx =>
val start = System.currentTimeMillis()
mapResponse { resp =>
// store response related metrics and return response
resp
} & handleExceptions(exceptionHandler)
}
private val exceptionHandler: ExceptionHandler = {
def handle(e: Throwable, responseCode: StatusCode, errorMessage: Option[String]): Route = {
extractRequest { request =>
val response = (responseCode, errorMessage) match {
case (InternalServerError, _) => "Internal Server Error"
case (_, Some(message)) => message
case _ => "Bad Request"
}
complete(HttpResponse(responseCode, entity = response))
}
}
ExceptionHandler {
case e#AError(description) => handle(e, BadRequest, Some(description))
case e: BError => handle(e, InternalServerError, Some(e.errorMessage))
case e: CError => handle(e, BadRequest, Some(e.errorMessage))
case e: DError => handle(e, BadRequest, Some(e.errorMessage))
case e: EError => handle(e, BadRequest, Some(e.errorMessage))
case e#FException(filter) => handle(e, BadRequest, Some(s"bla"))
case other => handle(other, InternalServerError, Option(other.getMessage))
}
}
What I am getting though is a 401 Unauthorized. How can this be?
As I was debugging the code I noticed that the control flow never enters my exception handler - I added breakpoints everywhere inside...

The problem with your code is that, after the rejection of request in the unauthenticated directive, the match happens against an authenticated route with the same url. So the authentication fails and results in 401 unauthorized instead of 404.
For solving it, you need to prevent this match against the authenticated route, after the failure of the unauthenticated route with the GET method, by wrapping it inside post, put, and delete routes so that the GET requests cannot reach it.
So it can be written as
private val routes: Route =
concat(
pathEnd {
get {
handleErrorsAndReport("list_foos") {
}
}
},
path(Segment) { fooId =>
get {
handleErrorsAndReport("get_foo") {
rejectEmptyResponse(
complete(service.do(fooId))
)
}
}
},
post {
pathEnd {
authenticateBasic(
realm = "Secure scope",
scopesAuthenticator
) { scopes =>
handleErrorsAndReport("create_foo") {
}
}
}
},
put{
path(Segment) { fooId =>
authenticateBasic(
realm = "Secure scopes",
scopesAuthenticator
) { scopes =>
handleErrorsAndReport("update_foo") {
}
}
}
},
delete{
path(Segment) { fooId =>
authenticateBasic(
realm = "Secure scopes",
scopesAuthenticator
) { scopes =>
handleErrorsAndReport(“delete_foo") {
}
}
}
}
)

Related

Akka HTTP Route Handling [duplicate]

This question already has an answer here:
Akka-HTTP route not found?
(1 answer)
Closed 1 year ago.
I have the following route setup
val routes = protectedRoute("wallet") { user =>
concat {
path("wallet" / "deposit") {
get {
completeEitherT(walletService.deposit(user._id, "dollars", 50))
}
}
path("wallet") {
get {
completeEitherT(walletService.getForUser(user._id))
}
}
}
}
The completeEitherT function is as follows
def completeEitherT[T](t: EitherT[Future, DatabaseError, T])(implicit marsh: ToResponseMarshaller[T]): Route = {
onSuccess(t.value) {
case Left(x: DatabaseErrors.NotFound) =>
logger.error(x.toString)
complete(StatusCodes.NotFound)
case Left(error) => complete(StatusCodes.InternalServerError)
case Right(value) => complete(value)
}
}
The protectedRoute Directive is:
def protectedRoute(permissions: String*): Directive1[User] = new Directive1[User] {
override def tapply(f: (Tuple1[User]) => Route): Route = {
headerValueByName("Authorization") { jwt =>
Jwt.decode(jwt, jwtSecret, List(algo)) match {
case Failure(_) =>
logger.error("Unauthorized access from jwtToken:", jwt)
complete(StatusCodes.Unauthorized)
case Success(value) =>
val user = JsonParser(value.content).convertTo[User]
if (user.roles.flatMap(_.permissions).exists(permissions.contains)) f(Tuple1(user))
else complete(StatusCodes.Forbidden)
}
}
}
}
The issue that I am having is that whichever path is defined first results in a 404 when called via Postman.
The requested resource could not be found.
This is not a response from completeEitherT as it does not log the error
How do I define two or more paths inside the same directive?
Please mark as duplicate, I could not find this on Google Search but SO showed this as related.
Answer
Essentially I am missing a ~ between the paths
val routes = protectedRoute("wallet") { user =>
concat {
path("wallet" / "deposit") {
get {
completeEitherT(walletService.deposit(user._id, "dollars", 50))
}
} ~
path("wallet") {
get {
completeEitherT(walletService.getForUser(user._id))
}
}
}
}

Refreshing access token with multiple requests

Im struggling with getting axios interceptors to work.
When my token expires, i need it to refresh the access token and retry the original request once the token is refreshed.
I have this part working.
The problem is if i have concurrent api calls it will only retry the first request when the token was first invalid.
Here is my interceptor code:
export default function execute() {
let isRefreshing = false
// Request
axios.interceptors.request.use(
config => {
var token = Storage.getAccessToken() //localStorage.getItem("token");
if (token) {
console.log('Bearer ' + token)
config.headers['Authorization'] = 'Bearer ' + token
}
return config
},
error => {
return Promise.reject(error)
}
)
// Response
axios.interceptors.response.use(
response => {
return response
},
error => {
const originalRequest = error.config
// token expired
if (error.response.status === 401) {
console.log('401 Error need to reresh')
originalRequest._retry = true
let tokenModel = {
accessToken: Storage.getAccessToken(),
client: 'Web',
refreshToken: Storage.getRefreshToken()
}
//Storage.destroyTokens();
var refreshPath = Actions.REFRESH
if (!isRefreshing) {
isRefreshing = true
return store
.dispatch(refreshPath, { tokenModel })
.then(response => {
isRefreshing = false
console.log(response)
return axios(originalRequest)
})
.catch(error => {
isRefreshing = false
console.log(error)
// Logout
})
} else {
console.log('XXXXX')
console.log('SOME PROBLEM HERE') // <------------------
console.log('XXXXX')
}
} else {
store.commit(Mutations.SET_ERROR, error.response.data.error)
}
return Promise.reject(error)
}
)
}
I'm not sure what i need in the else block highlighted above.
EDIT:
When I do
return axios(originalRequest)
in the else block it works, however im not happy with the behaviours. It basically retries all the requests again and again until the token is refreshed.
I would rather it just retried once after the token had been refreshed
Any ideas
Thanks
You can just have additional interceptor which can refresh token and execute your pending requests.
In this, countDownLatch class can help.
Here is sample Interceptor code,
class AutoRefreshTokenRequestInterceptorSample() : Interceptor {
companion object {
var countDownLatch = CountDownLatch(0)
var previousAuthToken = ""
const val SKIP_AUTH_TOKEN = "SkipAccessTokenHeader"
const val AUTHORIZATION_HEADER = "AUTHORIZATION_HEADER_KEY"
}
#Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response? {
val request = chain.request()
if (shouldExecuteRequest(request)) {
// Execute Request
val response = chain.proceed(request)
if (!response.isSuccessful) {
// Failed Case
val errorBody = response.peekBody(java.lang.Long.MAX_VALUE).string()
val error = parseErrorModel(errorBody)
// Gives Signal to HOLD the Request Queue
countDownLatch = CountDownLatch(1)
handleError(error!!)
// After updating token values, execute same request with updated values.
val updatedRequest = getUpdatedRequest(request)
// Gives Signal to RELEASE Request Queue
countDownLatch.countDown()
//Execute updated request
return chain.proceed(updatedRequest)
} else {
// success case
return response
}
}
// Change updated token values in pending request objects and execute them!
// If Auth header exists, and skip header not found then hold the request
if (shouldHoldRequest(request)) {
try {
// Make this request to WAIT till countdown latch has been set to zero.
countDownLatch.await()
} catch (e: Exception) {
e.printStackTrace()
}
// Once token is Updated, then update values in request model.
if (previousAuthToken.isNotEmpty() && previousAuthToken != "newAccessToken") {
val updatedRequest = getUpdatedRequest(request)
return chain.proceed(updatedRequest)
}
}
return chain.proceed(request)
}
private fun handleError(error: ErrorDto) {
// update your token as per your error code logic
//Here it will make new API call to update tokens and store it in your local preference.
}
/***
* returns Request object with updated token values.
*/
private fun getUpdatedRequest(request: Request): Request {
var updateAuthReqBuilder: Request.Builder = request.newBuilder()
var url = request.url().toString()
if (url.contains(previousAuthToken.trim()) && previousAuthToken.trim().isNotEmpty()) {
url = url.replace(previousAuthToken, "newAccessToken")
}
updateAuthReqBuilder = updateAuthReqBuilder.url(url)
// change headers if needed
return updateAuthReqBuilder.build()
}
private fun shouldExecuteRequest(request: Request) =
shouldHoldRequest(request) && isSharedHoldSignalDisabled()
/**
* If count down latch has any value then it is reported by previous request's error signal to hold the whole pending chain.
*/
private fun isSharedHoldSignalDisabled() = countDownLatch.count == 0L
private fun shouldHoldRequest(request: Request) = !hasSkipFlag(request) && hasAuthorizationValues(request)
private fun hasAuthorizationValues(request: Request) = isHeaderExist(request, AUTHORIZATION_HEADER)
private fun hasSkipFlag(request: Request) = isHeaderExist(request, SKIP_AUTH_TOKEN)
private fun isHeaderExist(request: Request, headerName: String): Boolean {
return request.header(headerName) != null
}
private fun parseErrorModel(errorBody: String): Error? {
val parser = JsonParser()
// Change this logic according to your requirement.
val jsonObject = parser.parse(errorBody).asJsonObject
if (jsonObject.has("Error") && jsonObject.get("Error") != null) {
val errorJsonObj = jsonObject.get("Error").asJsonObject
return decodeErrorModel(errorJsonObj)
}
return null
}
private fun decodeErrorModel(jsonObject: JsonObject): Error {
val error = Error()
// decode your error object here
return error
}
}
This is how I do:
let isRefreshing = false;
let failedQueue = [];
const processQueue = (error, token = null) => {
failedQueue.forEach(prom => {
if (error) {
prom.reject(error);
} else {
prom.resolve(token);
}
});
failedQueue = [];
};
axios.interceptors.response.use(
response => response,
error => {
const originalRequest = error.config;
if (error.response.status === 400) {
// If response is 400, logout
store.dispatch(logout());
}
// If 401 and I'm not processing a queue
if (error.response.status === 401 && !originalRequest._retry) {
if (isRefreshing) {
// If I'm refreshing the token I send request to a queue
return new Promise((resolve, reject) => {
failedQueue.push({ resolve, reject });
})
.then(() => {
originalRequest.headers.Authorization = getAuth();
return axios(originalRequest);
})
.catch(err => err);
}
// If header of the request has changed, it means I've refreshed the token
if (originalRequest.headers.Authorization !== getAuth()) {
originalRequest.headers.Authorization = getAuth();
return Promise.resolve(axios(originalRequest));
}
originalRequest._retry = true; // mark request a retry
isRefreshing = true; // set the refreshing var to true
// If none of the above, refresh the token and process the queue
return new Promise((resolve, reject) => {
// console.log('REFRESH');
refreshAccessToken() // The method that refreshes my token
.then(({ data }) => {
updateToken(data); // The method that sets my token to localstorage/Redux/whatever
processQueue(null, data.token); // Resolve queued
resolve(axios(originalRequest)); // Resolve current
})
.catch(err => {
processQueue(err, null);
reject(err);
})
.then(() => {
isRefreshing = false;
});
});
}
return Promise.reject(error);
},
);
I don't know what is the schema of your token (after decrypted) but one of the attributes which is a good practice to keep is the exp "expiration_date".
Said so, having the expiration date you can know when you should refresh your token.
Without understanding your architecture is hard to inform the right solution. But let's say you are doing everything manually, usually onIdle/onActive is when we check if the user session is still ok, so at this time you could use the token info to know if you should refresh its value.
It is important to understand this process because the token should be refreshed only if the user is constantly active and it is about to expire (like 2min before).
Please refer to angular version of the code for which i was facing the same problem and after changing many approaches this was my final code which is working at its best.
Re Initaite the last failed request after refresh token is provided

Akka Http return different type of response based on Accept header

I'm novice to scala and Akka-Http. Experimenting Akka-Http for writing rest services. I have to return json or protobuf based on the Accept header.
optionalHeaderValueByName("Accept"){ contentType =>
if(contentType == Some(protoEncode)) {
complete {
NewsService.getNewsList().map {
case stories: List[Story] => HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray))
}
}
} else {
complete {
NewsService.getNewsList().map {
case stories: List[Story] => StoryList(stories)
}
}
}
As you can see the code repetition is happening can anyone suggest what could be the best way to optimise and generalise design to avoid such situation.
The simplest way is to move the check inside the body.
optionalHeaderValueByName("Accept"){ contentType =>
complete {
NewsService.getNewsList().map {
case stories: List[Story] =>
if(contentType == Some(protoEncode)) {
HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray))
} else
StoryList(stories)
}
}
}
Figured it out.
optionalHeaderValueByName("Accept") { contentType =>
onSuccess(NewsService.getNewsList()) {
case stories: List[Story] => contentType match {
case Some(protoEncodingString) => complete(HttpResponse(entity = HttpEntity(ContentType(protoEncoding), StoryList(stories).toProto().build().toByteArray)))
case _=> complete(StoryList(stories))
}
}
}

Nested queries with ReactiveMongo

I have an article collection where fields "title" and "publication" has a unique combined key constraint.
When calling insertOrUpdateArticle(a: Article) it will first try to insert it, in case it hits the constraint, it should update the article - if needed.
However, I'm stuck before that. Current error is:
Error:(88, 57) type mismatch;
found : scala.concurrent.Future[scala.concurrent.Future[Boolean]]
required: Boolean
col_article.find(selector).one[Article].map {
Source:
def insertOrUpdateArticle(a: Article): Future[Boolean] = {
// try insert article
col_article.insert[Article](a).map {
// article inserted
lastError => {
println("Article added.")
true
}
}.recover {
case lastError: LastError =>
// check if article existed
lastError.code.get match {
case 11000 => {
// article existed (duplicate key error)
// load old article
val selector = BSONDocument(
"title" -> BSONString(a.title),
"publication" -> BSONString(a.publication)
)
col_article.find(selector).one[Article].map {
case Some(old_a: Article) => {
// TODO: compare a with old_a
// TODO: if a differs from old_a, update
Future(true)
}
case None => {
// something went wrong
Future(false)
}
}
}
case _ => {
println("DB.insertOrUpdateArticle() unexpected error code when inserting: " + lastError.code.get)
false
}
}
case ex =>
println("DB.insertOrUpdateArticle() unexpected exception when inserting: " + ex)
false
}
}
I'm unsure what to do here. The code should return Future(true) if the article was saved or updated, false otherwise. There's something with reactivemongo and/or scala futures I'm missing out here.
Using recoverWith to create new Future is the solution, modified code:
def insertOrUpdateArticleOld(a: Article): Future[Boolean] = {
// try insert article
col_article.insert[Article](a).map {
// article inserted
lastError => {
println("Article added.")
true
}
}.recoverWith {
case lastError: LastError =>
// check if article existed
lastError.code.get match {
case 11000 => {
// article existed (duplicate key error)
// load old article
val selector = BSONDocument(
"title" -> BSONString(a.title),
"publication" -> BSONString(a.publication)
)
col_article.find(selector).one[Article].flatMap {
case Some(old_a: Article) => {
// TODO: compare a with old_a
// TODO: if a differs from old_a, update
Future(true)
}
case None => {
// something went wrong
Future(false)
}
}
}
case _ => {
println("DB.insertOrUpdateArticle() unexpected error code when inserting: " + lastError.code.get)
Future(false)
}
}
case ex =>
println("DB.insertOrUpdateArticle() unexpected exception when inserting: " + ex)
Future(false)
}
}

How to create Custom Directive by composing multiple directives in spray

I would like to write a custom directive for all get, post,put and delete requests, because all requests needs authorization. To keep code DRY, I want to abstract those boilerplate(I have to authorize more than 100 requests). I could handle all Get Requests as follows
def method1 = Try("hi") // controller methods
def method2 = Try("hello")
path("getData1") {
handleGetRequest(method1)
}
path("getData2") {
handleGetRequest(method2)
}
def customGetDirective: Directive0 = {
headerValueByName("token").flatMap { token =>
authorize(checkAuthorization(token, ""))
get.hflatMap {x=>
respondWithMediaType(`application/json`)
}
}
}
def handleGetRequest(fn: => Try[_]) = {
customGetDirective { ctx=>
val result = fn
val json = //result can be coverted to json
ctx.complete(json)
}
}
I want to write a similar Generic directive for POST request, so that I could use
path("postData1") {
handlePostRequest(saveToDb)
}
def handlePostRequest(fn: => Try[_]) = {
customPostDirective { (ctx, JsonData)=>
//.......
ctx.complete(json)
}
}
but, I dont know how to get RequestContext and JsonData as tuple
I can write like this,
entity(as[String]) { jsonData =>
customPostDirective{ ctx=>
}
}
If I get a tuple it will be more useful.
Thank you.