Spray(14)Simple/Free/Complex Auth

Spray(14)Simple/Free/Complex Auth
 
We can have different auth in our spray framework.
Only Simple and Complex Auth need to have implementation class based on that.
 
In the AuthDirectives class, we need these kind of codes.
def localpointSimpleAuth = authenticate(new BrandUserSimpleSigAuthenticator(authDirectory)) & pathPrefix(Version) &optionalHeaderValueByName("Origin")
 
def localpointAuth = authenticate(new BrandUserSignatureAuthenticator(authDirectory)) & pathPrefix(Version) & optionalHeaderValueByName("Origin")
 
In the implementation, we usually just get some info from header and validate based on that.
package com.sillycat.localpoint.auth
 
import com.sillycat.localpoint.model.BrandUser
import org.joda.time.DateTime
 
import scala.concurrent.{ Future, ExecutionContext }
import spray.routing.authentication._
import com.sillycat.localpoint.auth.model._
import com.sillycat.localpointauth.directory.AuthDirectory
import com.sillycat.localpoint.auth.util.BrandCodeExtractor
import spray.http._
import spray.http.HttpHeaders.Authorization
import spray.util.pimpSeq
import com.typesafe.scalalogging.slf4j.Logging
import spray.routing.AuthenticationFailedRejection
import spray.routing.RequestContext
import scala.Some
import spray.routing.AuthenticationFailedRejection
import spray.routing.RequestContext
import scala.Some
import spray.routing.directives.{ RouteDirectives, MiscDirectives, BasicDirectives, MarshallingDirectives }
import spray.routing.directives.BasicDirectives._
import spray.routing.AuthenticationFailedRejection
import spray.routing.RequestContext
import scala.Some
import shapeless.{ HNil, :: }
import shapeless._
import spray.httpx.marshalling._
import spray.httpx.unmarshalling._
import spray.http._
 
class BrandUserSimpleSigAuthenticator(authDirectory: AuthDirectory)(implicit val executionContext: ExecutionContext) extends ContextAuthenticator[BrandUserWithPrivileges]
    with Logging {
 
  def apply(ctx: RequestContext) = {
 
    val authRequestOption = getAuthRequest(ctx)
 
    BrandCodeExtractor(ctx.request.uri.authority.host.address) match {
      case Some(b) => {
        authRequestOption match {
          case Some(x) => {
            checkSimpleSig(x, b)
          }
          case _ => {
            logger.warn("authenticate fail, parse header fail.")
            Future(Left(AuthenticationFailedRejection("Realm")))
          }
        }
      }
      case _ => {
        logger.warn("authenticate fail, system can not parse the brand code from host URL.")
        Future(Left(AuthenticationFailedRejection("Realm")))
      }
    }
  }
 
  def getAuthRequest(ctx: RequestContext): Option[String] = {
    val uri = ctx.request.uri.path.toString
 
    val authHeader = ctx.request.headers.findByType[`Authorization`]
 
    val tokenString = authHeader match {
      case Some(x) => {
        logger.debug("Header is there, try get token string from header " + x)
        x.value
      }
      case _ => {
        logger.debug("Header is empty, Body is empty.")
        ""
      }
    }
    Some(tokenString)
  }
 
  def checkSimpleSig(authRequest: String, brandCode: String) = {
    Future {
      // first load the user information to get the appId/ apisecretkey/ consolekey
      authDirectory.gebBrandByCode(brandCode) match {
        case Some(brand) => {
          if ((QABrands.contains(brandCode)) || (brand.apiSecretKey == authRequest)) {
            val privileges_set = Set("RESOURCE_" + "API", "RESOURCE_" + brandCode)
            val brandUser = BrandUser(None, 1l, "", "", "", true, "", "", "", false, false, true, false, DateTime.now, 0, 0)
            val user = BrandUserWithPrivileges(brandUser, brandCode, privileges_set)
            Right(user)
          } else {
            logger.warn("authenticate fail, simple signature error, AuthRequest String=" + authRequest)
            Left(AuthenticationFailedRejection("Realm"))
          }
        }
        case _ => {
          logger.warn("failed to retrieve auth info with brand '%s'".format(brandCode))
          Left(AuthenticationFailedRejection("Realm"))
        }
      }
    }
  }
 
}
 
When we build the router in Spray, we will build the 3 types of auth.
 
package com.sillycat.localpoint.console.api
 
import akka.actor.Actor
import akka.actor.ActorSystem
import akka.actor.Props
import akka.actor.actorRef2Scala
import akka.io.IO
import akka.routing.FromConfig
import com.sillycat.localpoint.actors.AttributeDBImportActor
import spray.can.Http
import com.sillycat.localpoint.auth.LocalpointAuthDirectives
import com.sillycat.localpoint.auth.service.AbstractAuthService
import spray.routing.{ Directives, HttpService }
import com.typesafe.config.ConfigFactory
import com.sillycat.localpoint.model._
import com.sillycat.localpoint.auth.util.ResponseHeaderUtil
import com.sillycat.localpointauth.directory.{ MultiStoreUserRepositoryComponent, AuthDirectory }
 
object LocalpointBridgeAPIServer extends App {
 
  implicit val system = ActorSystem()
 
  val config = ConfigFactory.load()
  assert(Profile.env == "environment." + config.getString("build.env"))
 
  val serverAddress: String = config.getString("server.address")
  val serverPort: Int = config.getInt("server.port")
  val dal: DAL = DAL()
 
  val handler = system.actorOf(Props[LocalpointBridgeAPIServiceActor])
 
  system.actorOf(Props[AttributeDBImportActor].withRouter(FromConfig()), name = "AttributeDBImportRouter")
 
  IO(Http) ! Http.Bind(handler, serverAddress, serverPort)
 
}
 
class LocalpointBridgeAPIServiceActor extends Actor with LocalpointConnector {
  def actorRefFactory = context
 
  def receive = runRoute(authSimpleRoute ~ authComplexRoute ~ authFreeRoute ~ baseOptions)
}
 
trait LocalpointConnector extends HttpService
    with AttributeMetadataService
    with CampaignService
    with AttributeService
    with ProfileService
    with DeviceIdentifierService
    with LocationService
    with TagService
    with LocalpointAuthDirectives
    with Directives {
 
  override implicit val dal: DAL = DAL.apply
 
  val authDirectory = new AuthDirectory with MultiStoreUserRepositoryComponent {}
 
  def baseOptions = {
    optionalHeaderValueByName("Origin") { originHeader =>
      respondWithHeaders(ResponseHeaderUtil.getCrossDomainHeaders(originHeader): _*) {
        options {
          complete {
            "OK"
          }
        }
      }
    }
  }
 
  val authFreeRoute = {
      optionalHeaderValueByName("Origin") { originHeader =>
        respondWithHeaders(ResponseHeaderUtil.getCrossDomainHeaders(originHeader): _*) {
          attributeAuthFreeRoutes()
        }
      }
  }
 
  val authSimpleRoute = {
      localpointSimpleAuth { (user, version, originHeader) =>
        respondWithHeaders(ResponseHeaderUtil.getCrossDomainHeaders(originHeader): _*) {
          attributeAuthSimpleRoutes(user, version)
        }
      }
  }
 
  val authComplexRoute = {
    //localpointAuth { (user, version) =>
    localpointAuth { (user, version, originHeader) =>
      respondWithHeaders(ResponseHeaderUtil.getCrossDomainHeaders(originHeader): _*) {
        authorize(verifyPrivileges(_, user)) {
          attributeMetadataRoutes(user, version) ~
            attributeRoutes(user, version)
        }
      }
    }
  }
}
 
References:
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值