softwaremill / akka-http-session

Web & mobile client-side akka-http sessions, with optional JWT support

Home Page:https://softwaremill.com/open-source/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

custom header

fintis opened this issue · comments

commented

Please I can't seem to see my custom headers. Anything I am doing wrong? I have configured as follows:

akka { loglevel = INFO stdout-loglevel = INFO loggers = ["akka.event.slf4j.Slf4jLogger"] default-dispatcher { fork-join-executor { parallelism-min = 8 } } test { timefactor = 1 } actor { deployment { /ServiceManagerRouter { router = "round-robin" nr-of-instances = 20 } } } http { session { server-secret = "####......###" header { send-to-client-name = "X-BLAH1" get-from-client-name = "Y-BLAH2" } refresh-token { cookie { name = "_refreshtoken" domain = none path = / secure = false http-only = true } header { send-to-client-name = "X-BLAH" get-from-client-name = "R-Y-BLAH" } max-age = 30 days remove-used-token-after = 5 seconds } } } }

Are you using the correct transport in the directives, e.g. setSession(oneOff, usingHeaders, sessionContent)?

commented

Hi,

Here is a code snippet showing how I have implemented...

trait RestApi extends RepositorySupport {
  implicit val system = GlobalInjector.getInjector.instance[ActorSystem]
  implicit val timeout = Timeout(60.seconds)

  val sessionConfig = SessionConfig.fromConfig()
  implicit val sessionManager = new SessionManager[ScSession](sessionConfig)

  implicit val refreshTokenStorage = new RefreshTokenStorage[ScSession] {
    override def lookup(selector: String): Future[Option[RefreshTokenLookupResult[ScSession]]] = {

      tokenRepo.tokenService.findSecureTokenBySelector(selector)
    }

    override def schedule[S](after: Duration)(op: => Future[S]): Unit = {
      ???
    }

    override def store(data: RefreshTokenData[ScSession]): Future[Unit] = {
      val token = Token(secureToken = Some(SecureToken(session = data.forSession, selector = data.selector, tokenHash = data.tokenHash, expires = data.expires)))
      tokenRepo.tokenService.createSecureToken(token)
    }

    override def remove(selector: String): Future[Unit] = {
      tokenRepo.tokenService.deleteSecureTokenBySelector(selector)
    }
  }
  def mySetSession(v: ScSession) = {
    println(s"setting session ${v.token}")
    setSession(refreshable, usingHeaders, v)
  }

  val myRequiredSession = requiredSession(refreshable, usingHeaders)
  val myInvalidateSession = invalidateSession(refreshable, usingHeaders)

  def serviceManager(implicit system: ActorSystem) = system.actorOf(Props[ServiceManager])


}

The trait above is inherited in the route as below

trait AuthRoutes extends CORSSupport with RestApi {


  def authRoutes(implicit executionContext: ExecutionContext): Route = {
    cors {
      pathPrefix("api" / "v1") {
        (post & path("login" / Segment)) { user =>
          entity(as[LoginDTO]) { login =>
            complete {
              serviceManager.ask(Authenticate(login, user)).mapTo[LoginMessage].map {
                case msg: LoginSuccess => mySetSession(ScSession(msg.token))
                  HttpResponse(200, entity = msg.token)
                case LoginFailure => HttpResponse(400, entity = "Bad request")
                case _ => HttpResponse(400, entity = "Bad request")
              }
            }
          }
        } ~

I am sorry for the late response...

Many thanks for your help

I'm not sure if I'm reading your code correctly but mySetSession is a directive and should be used as such; it doesn't have any side-effects, it needs to wrap other handlers that should complete the request.

I think you are just calling mySetSession and the returning the response HttpResponse as two separate statements, so the results of mySetSession are ignored.

I think the correct usage would be:

onSuccess(serviceManager.ask(Authenticate(login, user)).mapTo[LoginMessage]) {
  case msg: LoginSuccess => 
    mySetSession(ScSession(msg.token)) {
      complete(HttpResponse(...))
    }
  case ... => complete(...)
}
commented

@adamw oaf! I think you are right. Didn't reason it that way.. I will give it a try and let you know how it goes.

commented

@adamw Many thanks for your prompt intervention... 👍

Still don't know why i didn't use it as a directive as it was very clear in the example.

I guess I got carried away with the ask pattern viz-a-viz. I will close now!

Cheers