I have the following backend. If going to the "localhost:8080", the login page is loaded by redirecting from "/" to "login". Login page is loaded. At submitting the login form, the "perform-login" is called. However, for some reason, there is no redirect to "storage" page. Why?
P.S. If requesting the page "storage" manually, it is loaded. The problem is with the redirect from "login" page to "storage" page. Probably, it has something to do with setting the cookies, as this command also has the return type Route.
Scala version: 2.13.6,
Akka HTTP version: 10.2.6
object Backend {
def main(args: Array[String]) = {
implicit val system = ActorSystem(Behaviors.empty, "lowlevel")
// needed for the future map/flatmap in the end
implicit val executionContext: ExecutionContext = system.executionContext
val topLevelRoute: Route =
concat(
pathSingleSlash {
redirect("login", StatusCodes.PermanentRedirect)
},
path("login") {
complete("my login page")
},
path("storage") {
cookie("token") { tokenCookie =>
println("you managed to login, token:" + tokenCookie.value + "ENDLINE")
complete("my storage page")
}
},
path("perform-login") {
formFields("Username", "Password") { (username, password) =>
var isAbleToLogin = database.isUserLoggedIn(username, password)
if (isAbleToLogin == true) {
setCookie(HttpCookie("token", value="ThisIsMyStrongAccessToken")) {
//TODO: debug why does not redirect to main page
redirect("storage", StatusCodes.PermanentRedirect)
}
}
else {
reject(ValidationRejection("bad credentials"))
}
}
},
path(Remaining) { pathRest =>
reject(ValidationRejection("topLevelRoute, unknown path:" + pathRest + "ENDLINE"))
}
)
val binding = Http().newServerAt("localhost", 8080).bind(topLevelRoute)
println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
StdIn.readLine() // let it run until user presses return
binding
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
Solution:
When I was navigating to the "/" page, the redirect to the "/login" page happens due to the "document / redirect" request type (if analysing the network).
But, in case of redirecting from "/login" page to "/storage" page, the request is of type "xhr /redirect" that cannot be done on the server side, i.e. I had to add $(location).attr('href', 'storage') to my jQuery script to make it work.
Related
i have a route which needs an access token in its header to grant access to it for that i have this working code
def accessProtectedResource: server.Route =
path("access-protected-resource") {
get {
bearerToken { token =>
token match {
case Some(tokenValue) =>
complete(OK, routeResponseMessage.getResponse(OK.intValue,ServerMessages.AUTH_PASS,JsObject.empty))
case None => reject(AuthorizationFailedRejection)
}
}
}
}
private def bearerToken: Directive1[Option[String]] =
for {
authBearerHeader <- optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken)
xAuthCookie <- optionalCookie("X-Authorization-Token").map(_.map(_.value))
} yield authBearerHeader.orElse(xAuthCookie)
private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
authHeader.collect {
case Authorization(OAuth2BearerToken(token)) => token
}
when i hit the route through postman in the Authorization tab i selected the type to Bearer Token and add the token and send the request and everything works fine now i want to unit test this route
for this i am looking at this
but i am confused how can i add the header in a proper way in my unit test here is my code
"pass route /access-protected-resource" in {
routeResponseMessage.getResponse(OK.intValue, ServerMessages.AUTH_PASS, JsObject.empty)
val originHeader = Authorization(OAuth2BearerToken("accessTokenString"))
Get("http://0.0.0.0:8083/get-user-token") ~> originHeader ~> authenticationController.route ~> check {
}
}
but my route is getting rejected
- pass route /access-protected-resource *** FAILED ***
[info] Request was rejected with rejection MethodRejection(HttpMethod(POST)) (CheckValidUserTokenExistsTest.scala:76)
how to do this correctly ?
How about using addCredential and testing only bearerToken method wrapped with Route.seal like this(https://github.com/ItoYo16u/scala-usage-playground/blob/master/src/test/scala/web/akka/JWTDirectivesSpec.scala)?
i have the following akka http rejection handling code taken from https://doc.akka.io/docs/akka-http/current/routing-dsl/rejections.html
val message = "The requested resource could not be found."
implicit def myRejectionHandler = RejectionHandler.newBuilder()
.handleNotFound {
complete(HttpResponse(NotFound
,entity = HttpEntity(ContentTypes.`application/json`, s"""{"rejection": "$message"}"""
)))
}.result()
val route: Route = handleRejections(myRejectionHandler) {
handleExceptions(myExceptionHandler) {
concat(
path("event-by-id") {
get {
parameters('id.as[String]) {
id =>
complete("id")
}
}
}
,
post {
path("create-event") {
entity(as[Event]) {
event =>
complete(OK, "inserted")
}
}
}
)
}
}
}
val bindingFuture = Http().bindAndHandle(route, hostName, port)
when i hit localhost:8080/random
i got the message
HTTP method not allowed, supported methods: POST
and when i select POST and hit localhost:8080/random
i got the message
{
"rejection": "The requested resource could not be found."
}
why i did not get the same message when my route request was GET ?
in the docs the handleNotFound was working with GET request https://doc.akka.io/docs/akka-http/current/routing-dsl/rejections.html
This is happens, probably because of order of directives, you are using: in your configuration if incoming request does not match with event-by-id URL path, then it goes to the next handler, which expects that request should have POST method first of all, because post directive goes first, before path("create-event").
What you can try to do is change directives order to the next one, for second route:
path("create-event") {
post {
entity(as[Event]) { event =>
complete(OK, "inserted")
}
}
}
Hope this helps!
How to implement Basic Authentication for web sockets using play framework.
I am creating a web socket using play framework.
I would like to do basic authentication and send 401 if authentication fails.
Below is my code and i am not able to send "{code=401, message=unauthorized access}" as response
def ChatServer(): WebSocket = WebSocket.accept[String, String] { request =>
if (Util.doBasicAuthentication(request.headers)) {
ActorFlow.actorRef { out =>
ChatActor.props(out)
}
} else throw new RuntimeException("Unauthorized Access")
}
Whenever authentication fails, i am not able to send the response back as "unauthorized access" instead i am ending up with exceptions
As described in the Play documentation, use WebSocket.acceptOrResult:
def socket = WebSocket.acceptOrResult[String, String] { request =>
Future.successful {
if (Util.doBasicAuthentication(request.headers)) {
Right(ActorFlow.actorRef { out =>
ChatActor.props(out)
})
} else {
Left(Unauthorized)
}
}
}
i am trying to insert data from form to database but on form submission control does not enter in fold(error, success) method and runs the statement after it and redirects it to other page
this is my controller method
def submitinfo = Action { implicit request =>
signupForm.bindFromRequest().fold(
errors => BadRequest(views.html.signup(errors)),
data => {
println("************enter sucess case *********************")
signupcc.insertData(data.name, data.username, data.email, data.password)
})
println("************Redirecting to sucess page *********************")
Redirect(routes.Application.success)
}
here is my routes file
# Home page
GET / controllers.Application.index
GET /signup controllers.Application.signup
POST /submit controllers.Application.submitinfo
GET /success controllers.Application.success
GET /signin controllers.Application.signin
please tell me what i am doing wrong
Redirect action should be part of sucess case inside fold method:
def submitinfo = Action { implicit request =>
signupForm.bindFromRequest().fold(errors => BadRequest(views.html.signup(errors)),
data => {
println("************enter sucess case *********************")
signupcc.insertData(data.name, data.username, data.email, data.password)
println("************Redirecting to sucess page *********************")
Redirect(routes.Application.success)
})
}
I have a similar problem to this person and I am unsure why.
my post action is called from a form submission and the controller code
def processFreeDoc = UserAwareAction {
implicit request => {
userEmailForm.bindFromRequest.fold(
formWithErrors => {
Logger.error("Error processing the form %s "format formWithErrors.errors)
Redirect(routes.Application.index)
},
data => {
val sessionProduct = getSessionUnProcessedProduct(data.sessionId, data.documentName)
if(sessionProduct != null){
Logger.info("Found")
sessionProduct.updateProcessing(data.emailAddress, data.sessionId)
Redirect(routes.Application.index)
}
else
Logger.info("Nothing found")
Redirect(routes.Application.checkoutFree(data.sessionId))
}
)
}
}
is skipped entirely. There are no errors in the IDE(IDEA) console and the breakpoint at the entry of the method is not reached so none of the log messages are seen.
EDIT :
The relevant route in the routes file - POST /processFreeDoc controllers.Application.processFreeDoc