当前位置: 首页>>代码示例>>Scala>>正文


Scala Authorization类代码示例

本文整理汇总了Scala中akka.http.scaladsl.model.headers.Authorization的典型用法代码示例。如果您正苦于以下问题:Scala Authorization类的具体用法?Scala Authorization怎么用?Scala Authorization使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Authorization类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: extractBearerToken

//设置package包名称以及导入依赖的类
package com.github.cupenya.microservices.sdk.authentication

import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.{AuthorizationFailedRejection, Directive1, Directives}
import com.github.cupenya.microservices.sdk.logging.Logging

import scala.concurrent.ExecutionContext

trait AuthorizationDirectives extends Logging {
  self: Directives =>

  implicit val ec: ExecutionContext

  // TODO: dep injection
  private val tokenVerifier = new JwtTokenVerifier

  private def extractBearerToken(authHeader: Option[Authorization]): Option[String] =
    authHeader.collect {
      case Authorization(OAuth2BearerToken(token)) => token
    }

  def authorized: Directive1[AuthInfo] = {
    optionalHeaderValueByType(classOf[Authorization]).map(extractBearerToken).flatMap {
      case Some(token) =>
        onComplete(tokenVerifier.verifyToken(token)).flatMap { x =>
          x.map(authInfo => provide(authInfo))
            .recover {
              case ex =>
                log.error("Couldn't log in using provided authorization token", ex)
                reject(AuthorizationFailedRejection).toDirective[Tuple1[AuthInfo]]
            }
            .get
        }
      case None =>
        reject(AuthorizationFailedRejection)
    }
  }
} 
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:39,代码来源:AuthorizationDirectives.scala

示例2: AccessToken

//设置package包名称以及导入依赖的类
package com.orendain.sraw.model

import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import org.json4s.JsonAST._
import com.orendain.sraw.Connection
import com.orendain.sraw.api.AuthorizationAPI
import com.orendain.sraw.model.extract._


class AccessToken(val json: JObject) extends RedditObject {

  val accessToken = valString("access_token")
  val tokenType = valString("token_type")
  val expiresIn = valLong("expires_in")
  val refreshToken = valOp[String]("refresh_token")
  val scope = values("scope")

  val header = Authorization(OAuth2BearerToken(accessToken))

  val expiration = System.currentTimeMillis() + expiresIn
  def hasExpired = System.currentTimeMillis() > expiration

  def revoke()(implicit con: Connection) {
    val stub = refreshToken match {
      case Some(str) => AuthorizationAPI.revokeToken(refreshToken.get, "refresh_token")
      case None => AuthorizationAPI.revokeToken(accessToken, "access_token")
    }
    stub.process()
  }
} 
开发者ID:orendain,项目名称:sraw,代码行数:31,代码来源:AccessToken.scala

示例3: RegistryClient

//设置package包名称以及导入依赖的类
package net.ruippeixotog.scalafbp.protocol.registry

import scala.concurrent.{ ExecutionContext, Future }

import akka.actor.ActorSystem
import akka.event.slf4j.SLF4JLogging
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
import akka.http.scaladsl.model.{ HttpRequest, HttpResponse, RequestEntity }
import akka.stream.Materializer
import fommil.sjs.FamilyFormats._

class RegistryClient(baseUrl: String = "http://api.flowhub.io") extends SLF4JLogging {

  def register(runtime: Runtime, token: String)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): Future[HttpResponse] = {
    log.debug(s"PUT $baseUrl/runtimes/${runtime.id}")
    Marshal(runtime).to[RequestEntity].flatMap { entity =>
      Http().singleRequest(HttpRequest(
        PUT,
        s"$baseUrl/runtimes/${runtime.id}",
        List(Authorization(OAuth2BearerToken(token))),
        entity))
    }
  }

  def unregister(runtimeId: String, token: String)(implicit system: ActorSystem, mat: Materializer): Future[HttpResponse] = {
    log.debug(s"DELETE $baseUrl/runtimes/$runtimeId")
    Http().singleRequest(HttpRequest(
      DELETE,
      s"$baseUrl/runtimes/$runtimeId",
      List(Authorization(OAuth2BearerToken(token)))))
  }
} 
开发者ID:ruippeixotog,项目名称:scalafbp,代码行数:37,代码来源:RegistryClient.scala

示例4: canAccessRoute

//设置package包名称以及导入依赖的类
package co.horn.alkes.auth

import akka.http.scaladsl.model.HttpMethod
import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST, PUT}
import akka.http.scaladsl.model.StatusCodes.{Forbidden, ServerError}
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import co.horn.alkes.config.Configuration
import co.horn.alkes.dao.DataHandler
import co.horn.alkes.dao.implementations.riak.RiakDataHandler
import co.horn.alkes.log.Logger
import co.horn.alkes.rest.Routes
import org.scalatest.{FunSpec, Matchers}
import org.scalatest.concurrent.Eventually

trait AuthTest extends FunSpec with Matchers with Eventually with ScalatestRouteTest with Routes {
  val config: Configuration = Configuration.get
  val dao: DataHandler      = new RiakDataHandler(config)
  val log: Logger           = config.log.tests

  // TODO: Define these all in just ONE spot. Need to keep DRY!
  val BASE_PATH: String  = "/" + config.app.name
  val FILE_PATH: String  = BASE_PATH + "/share/file"
  val LIST_PATH: String  = BASE_PATH + "/share/filelist"
  val META_PATH: String  = BASE_PATH + "/share/metadata"
  val THUMB_PATH: String = BASE_PATH + "/share/thumbnail"

  
  def canAccessRoute(token: OAuth2BearerToken, route: String, method: HttpMethod): Boolean = {
    method match {
      case GET =>
        Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case PUT =>
        Put(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case DELETE =>
        Get(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case POST =>
        Post(route).withHeaders(Authorization(token)) ~> Route.seal(routes) ~> check {
          status should not be a[ServerError]
          status != Forbidden
        }
      case m => throw new IllegalArgumentException(s"$m is not an HttpMethod accepted by Alkes.")
    }
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:56,代码来源:AuthTest.scala

示例5: LayerClient

//设置package包名称以及导入依赖的类
package com.jatescher.layer

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.{ Accept, Authorization, OAuth2BearerToken }
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.Materializer
import com.jatescher.layer.http.MediaRanges.LayerJsonMediaRange
import com.jatescher.layer.marshalling.Marshallers.{ ErrorResponseUnmarshaller, _ }
import com.jatescher.layer.models.{ ErrorResponse, Message }
import com.typesafe.config.Config
import scala.concurrent.{ ExecutionContext, Future }

class LayerClient(router: LayerRouter, config: Config)(implicit system: ActorSystem, materializer: Materializer, ec: ExecutionContext) {
  val LAYER_TOKEN = config.getString("layer.token")

  def sendMessage(message: Message): Future[Either[ErrorResponse, Message]] = {
    for {
      messageRequest <- sendMessageRequest(message)
      response <- executeRequest(messageRequest)
      messageOrErrorResponse <- unmarshallResponse(response)
    } yield messageOrErrorResponse
  }

  private def sendMessageRequest(message: Message): Future[HttpRequest] = {
    Marshal(message).to[RequestEntity].map { entity =>
      HttpRequest(
        method = HttpMethods.POST,
        uri = router.createMessageUrl(message.conversation),
        entity = entity,
        headers = List(
          Authorization(OAuth2BearerToken(LAYER_TOKEN)),
          Accept(LayerJsonMediaRange)
        )
      )
    }
  }

  protected def executeRequest(httpRequest: HttpRequest): Future[HttpResponse] = {
    Http().singleRequest(httpRequest)
  }

  private def unmarshallResponse(response: HttpResponse): Future[Either[ErrorResponse, Message]] = {
    val unmarshalledResponse = Unmarshal(response.entity)

    if (response.status == StatusCodes.Created) {
      unmarshalledResponse.to[Message].map(Right(_))
    } else {
      unmarshalledResponse.to[ErrorResponse].map(Left(_))
    }
  }

} 
开发者ID:jtescher,项目名称:layer-scala,代码行数:56,代码来源:LayerClient.scala

示例6: BacklogOAuthClientImpl

//设置package包名称以及导入依赖的类
package com.github.chaabaj.openid.apis.backlog

import akka.actor.ActorSystem
import akka.http.scaladsl.model.{HttpRequest, Uri}
import akka.http.scaladsl.model.Uri.Path
import akka.http.scaladsl.model.headers.{Authorization, OAuth2BearerToken}
import com.github.chaabaj.openid.HttpClient
import com.github.chaabaj.openid.oauth.{AccessTokenSuccess, Backlog, OAuthClient, SupportsIssuingAccessToken, SupportsOpenIDConnect}

import scala.concurrent.{ExecutionContext, Future}
import scala.concurrent.duration.FiniteDuration

trait BacklogOAuthClient
  extends OAuthClient
    with SupportsIssuingAccessToken
    with SupportsOpenIDConnect {
  override final type Provider = Backlog
  override type UserInfo = BacklogUserInfo
}

private class BacklogOAuthClientImpl(backlogUri: Uri)(implicit actorSystem: ActorSystem, timeout: FiniteDuration)
  extends BacklogOAuthClient {
  override val httpClient: HttpClient = HttpClient()
  override protected def accessTokenUrl: String = backlogUri.withPath(Path("/api/v2/oauth2/token")).toString()

  override def getUserInfo(token: AccessTokenSuccess)(implicit exc: ExecutionContext): Future[UserInfo] = {
    // TODO validate id_token
    val httpRequest = HttpRequest(
      uri = backlogUri.withPath(Path("/api/v2/users/myself"))
    ).withHeaders(Authorization(OAuth2BearerToken(token.accessToken)))
    httpClient.request(httpRequest)
      .map(_.convertTo[UserInfo])
  }
}

object BacklogOAuthClient {
  def apply(backlogUri: Uri)(implicit actorSystem: ActorSystem, timeout: FiniteDuration): BacklogOAuthClient =
    new BacklogOAuthClientImpl(backlogUri)
} 
开发者ID:chaabaj,项目名称:openid-scala,代码行数:40,代码来源:BacklogOAuthClient.scala

示例7: JsonRPCRequest

//设置package包名称以及导入依赖的类
package fr.acinq.eclair.blockchain.rpc

import java.io.IOException

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.{Authorization, BasicHttpCredentials}
import akka.http.scaladsl.unmarshalling.Unmarshal
import akka.stream.ActorMaterializer
import de.heikoseeberger.akkahttpjson4s.Json4sSupport._
import org.json4s.JsonAST.JValue
import org.json4s.{DefaultFormats, jackson}

import scala.concurrent.{ExecutionContext, Future}

// @formatter:off
case class JsonRPCRequest(jsonrpc: String = "1.0", id: String = "scala-client", method: String, params: Seq[Any])
case class Error(code: Int, message: String)
case class JsonRPCResponse(result: JValue, error: Option[Error], id: String)
case class JsonRPCError(error: Error) extends IOException(s"${error.message} (code: ${error.code})")
// @formatter:on

class BitcoinJsonRPCClient(user: String, password: String, host: String = "127.0.0.1", port: Int = 8332, ssl: Boolean = false)(implicit system: ActorSystem) {

  val scheme = if (ssl) "https" else "http"
  val uri = Uri(s"$scheme://$host:$port")

  implicit val materializer = ActorMaterializer()
  val httpClient = Http(system)
  implicit val serialization = jackson.Serialization
  implicit val formats = DefaultFormats

  def invoke(method: String, params: Any*)(implicit ec: ExecutionContext): Future[JValue] =
    for {
      entity <- Marshal(JsonRPCRequest(method = method, params = params)).to[RequestEntity]
      httpRes <- httpClient.singleRequest(HttpRequest(uri = uri, method = HttpMethods.POST).addHeader(Authorization(BasicHttpCredentials(user, password))).withEntity(entity))
      jsonRpcRes <- Unmarshal(httpRes).to[JsonRPCResponse].map {
        case JsonRPCResponse(_, Some(error), _) => throw JsonRPCError(error)
        case o => o
      } recover {
        case t: Throwable if httpRes.status == StatusCodes.Unauthorized => throw new RuntimeException("bitcoind replied with 401/Unauthorized (bad user/password?)", t)
      }
    } yield jsonRpcRes.result

  def invoke(request: Seq[(String, Seq[Any])])(implicit ec: ExecutionContext): Future[Seq[JValue]] =
    for {
      entity <- Marshal(request.map(r => JsonRPCRequest(method = r._1, params = r._2))).to[RequestEntity]
      httpRes <- httpClient.singleRequest(HttpRequest(uri = uri, method = HttpMethods.POST).addHeader(Authorization(BasicHttpCredentials(user, password))).withEntity(entity))
      jsonRpcRes <- Unmarshal(httpRes).to[Seq[JsonRPCResponse]].map {
        //case JsonRPCResponse(_, Some(error), _) => throw JsonRPCError(error)
        case o => o
      } recover {
        case t: Throwable if httpRes.status == StatusCodes.Unauthorized => throw new RuntimeException("bitcoind replied with 401/Unauthorized (bad user/password?)", t)
      }
    } yield jsonRpcRes.map(_.result)

} 
开发者ID:viacoin,项目名称:eclair,代码行数:60,代码来源:BitcoinJsonRPCClient.scala

示例8: TwilioSmsEngine

//设置package包名称以及导入依赖的类
package im.actor.server.sms

import scala.concurrent.{ ExecutionContext, Future }

import akka.actor.ActorSystem
import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.{ Authorization, BasicHttpCredentials }
import akka.stream.Materializer
import com.typesafe.config.Config

class TwilioSmsEngine(config: Config)(implicit system: ActorSystem, materializer: Materializer, http: HttpExt) extends SmsEngine {

  private val account = config.getString("account")
  private val token = config.getString("token")
  private val from = config.getString("from")

  implicit val ec: ExecutionContext = system.dispatcher

  private val baseUri = Uri(s"https://api.twilio.com/2010-04-01/Accounts/$account/Messages.json")

  private val authHeader = Authorization(BasicHttpCredentials(account, token))

  override def send(phoneNumber: Long, message: String): Future[Unit] = {
    val to = s"+${phoneNumber}"

    Marshal(FormData(Map("From" ? from, "To" ? to, "Body" ? message))).to[RequestEntity] flatMap { entity ?
      val request = HttpRequest(
        method = HttpMethods.POST,
        uri = baseUri,
        entity = entity
      ).withHeaders(authHeader)

      http.outgoingConnection("api.twilio.com", 443)

      val f = http.singleRequest(request) map {
        case HttpResponse(StatusCodes.Created, _, _, _) ? ()
        case resp ?
          throw new Exception(s"Wrong response: ${resp}")
      }

      f onFailure {
        case e ?
          system.log.error(e, "Failed to send sms through twilio")
      }

      f
    }
  }
} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:52,代码来源:TwilioSmsEngine.scala


注:本文中的akka.http.scaladsl.model.headers.Authorization类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。