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


Scala OAuth2BearerToken类代码示例

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


在下文中一共展示了OAuth2BearerToken类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: extractBearerToken

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

import akka.http.scaladsl.model.headers.{ Authorization, OAuth2BearerToken }
import akka.http.scaladsl.server.{ AuthorizationFailedRejection, _ }
import com.github.cupenya.hello.Logging

import scala.concurrent.ExecutionContext.Implicits.global

trait AuthorizationDirectives extends Logging {
  self: Directives =>

  // 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,项目名称:hello-world-microservice,代码行数:37,代码来源:AuthorizationDirectives.scala

示例4: 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

示例5: ReplyMessageRequest

//设置package包名称以及导入依赖的类
package bot.line.client

import akka.http.scaladsl.client.RequestBuilding
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.model._
import bot.line.json.MessagesJsonSupport
import bot.line.model.send.{Messages, TextMessage}

import scala.concurrent.ExecutionContext

case class ReplyMessageRequest(
                                accessToken: String,
                                replyToken: String,
                                message: String
                              ) extends MessagesJsonSupport {

  def httpRequest(implicit ec: ExecutionContext): HttpRequest = {
    val auth:HttpHeader = headers.Authorization(OAuth2BearerToken(accessToken))
    val content = Messages(
      replyToken = replyToken,
      messages = List(TextMessage(text = message))
    )
    RequestBuilding.Post(
      uri = "https://api.line.me/v2/bot/message/reply",
      content = content
    ).withHeaders(auth)
  }
} 
开发者ID:xoyo24,项目名称:akka-http-line-bot,代码行数:29,代码来源:ReplyMessageRequest.scala

示例6: TestWasatAuth

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

import akka.http.scaladsl.model.HttpMethods.{DELETE, GET, POST}
import akka.http.scaladsl.model.StatusCodes.ServerError
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.server.Route

class TestWasatAuth extends AuthTest {
  val auth: Authority = new WasatAuthority(config)

  describe("Alkes is able to communicate with Wasat") {
    ignore("WasatAuthority is responding to Alkes' PING calls") {
      Get(s"$BASE_PATH/auth") ~> Route.seal(routes) ~> check {
        status should not be a[ServerError]
      }
    }
  }

  describe("WasatAuthority should allow") {
    ignore("anyone to ping") {
      canAccessRoute(OAuth2BearerToken("a"), s"$BASE_PATH/ping", GET) shouldBe true
    }

    ignore("anyone to check the database is alive") {
      canAccessRoute(OAuth2BearerToken("b"), s"$BASE_PATH/database", GET) shouldBe true
    }

    ignore("anyone to accidentally use POST") {
      canAccessRoute(OAuth2BearerToken("c"), s"$BASE_PATH", POST) shouldBe true
    }

    ignore("anyone to stumble upon the wrong route") {
      canAccessRoute(OAuth2BearerToken("d"), s"$BASE_PATH/whoops/wrong/path", GET) shouldBe true
    }
  }

  describe("DummyAuthority should NOT allow") {
    ignore("anonymous users to Get server file lists") {
      canAccessRoute(OAuth2BearerToken("j"), s"$LIST_PATH", GET) shouldBe false
    }

    ignore("anonymous users to Delete server file lists") {
      canAccessRoute(OAuth2BearerToken("k"), s"$LIST_PATH", DELETE) shouldBe false
    }
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:47,代码来源:TestWasatAuth.scala

示例7: 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

示例8: 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

示例9: getOrders

//设置package包名称以及导入依赖的类
package com.example.order.client

import akka.http.scaladsl.HttpExt
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.model.{DateTime, Uri}
import akka.stream.{ActorMaterializer, ActorMaterializerSettings, Materializer}
import com.example.Orders.OrderResponse
import com.example.order.client.OrderClientImpl.OrderClientConfig

import scala.concurrent.Future

trait OrderClient {
  def getOrders(page:Int = 1, since:DateTime)(implicit fm: Materializer): Future[HttpResponse]
}

class OrderClientImpl(orderClientConfig: OrderClientConfig, http:HttpExt) extends OrderClient{

  val ordersUri:Uri = s"https://sandbox.epages.com/rs/shops/${orderClientConfig.shopId}/orders?resultsPerPage=50"

  override def getOrders(page: Int=1, since: DateTime)(implicit fm: Materializer): Future[HttpResponse] = {

    val auth = headers.Authorization(OAuth2BearerToken(orderClientConfig.token))
    val accept = headers.Accept(MediaTypes.`application/json`)
    var uri = ordersUri + s"&page=$page"
    since match {
      case DateTime.MinValue =>
      case _ =>
        val createdAfter = since.toIsoDateTimeString()
        uri += s"&createdAfter=$createdAfter"
    }
    http.singleRequest(HttpRequest(HttpMethods.GET, uri, List(auth, accept)))
  }
}

object OrderClientImpl {
  case class OrderClientConfig(token:String, shopId:String)
} 
开发者ID:mduesterhoeft,项目名称:hack16-order-geo-statistics-akka-scala,代码行数:39,代码来源:OrderClient.scala

示例10: securedAccess

//设置package包名称以及导入依赖的类
package restapi.http.routes.support

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import core.entities.{AuthTokenContext, BearerToken, User}
import restapi.http.routes.ApiContext

private[http] trait SecuredAccessSupport {

  def securedAccess(inner: AuthTokenContext => Route)(implicit apiCtx: ApiContext): Route = {
    extractCredentials {
      case Some(OAuth2BearerToken(token)) =>
        apiCtx.authenticate(BearerToken(token)) match {
          case Some(ctx) => inner(ctx)
          case None      => complete(StatusCodes.Unauthorized)
        }
      case _ => complete(StatusCodes.Unauthorized)
    }
  }

  def privateResourceAccess(ctx: AuthTokenContext, username: String)(inner: Route)(implicit apiCtx: ApiContext): Route = {
    apiCtx.findUserByName(username) match {
      case Some(User(id, _, _)) if id.equals(ctx.userId) => inner
      case _                                             => complete(StatusCodes.NotAcceptable)
    }
  }
} 
开发者ID:lymr,项目名称:fun-chat,代码行数:30,代码来源:SecuredAccessSupport.scala

示例11: GoogleOAuthClientImpl

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

import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.headers
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import com.github.chaabaj.openid.HttpClient
import com.github.chaabaj.openid.apis.google
import com.github.chaabaj.openid.oauth._

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

trait GoogleOAuthClient
  extends OAuthClient
   with SupportsIssuingAccessToken
   with SupportsOpenIDConnect {
  override final type Provider = Google
  override final type UserInfo = google.UserInfo
}

private class GoogleOAuthClientImpl(implicit actorSystem: ActorSystem, timeout: FiniteDuration)
  extends GoogleOAuthClient {
  override val httpClient: HttpClient = HttpClient()
  override protected def accessTokenUrl: String = "https://www.googleapis.com/oauth2/v4/token"

  override def getUserInfo(token: AccessTokenSuccess)(implicit exc: ExecutionContext): Future[UserInfo] = {
    // TODO validate id_token
    val httpRequest = HttpRequest(
      uri = "https://www.googleapis.com/oauth2/v3/userinfo"
    ).withHeaders(headers.Authorization(OAuth2BearerToken(token.accessToken)))
    httpClient.request(httpRequest)
      .map(_.convertTo[google.UserInfo])
  }
}

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

示例12: 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

示例13: RedditService

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

import java.util.UUID

import akka.actor.ActorSystem
import akka.http.scaladsl.model.headers.OAuth2BearerToken
import akka.stream.Materializer

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.util.Try

class RedditService(val apiWrapper: RedditApiWrapper)(implicit system: ActorSystem, ec: ExecutionContext, mat: Materializer) {

  import RedditDataModel._

  def validateSubreddit(name: String): Option[SubredditData] = {
    Try {
      val response = apiWrapper.requestSubredditInfo(SubredditData(name))
      response.dataAsSubredditData
    }.toOption
  }

  //todo comments are filtering out "t3" kinds, which are selfposts and links
  def getRecentCommentsForSubreddit(subredditData: SubredditData, limit: Int): Future[List[CommentData]] = {
    val response = apiWrapper.requestRecentCommentsForSubreddit(subredditData, limit)
    response.map(_.data.children.filter(_.kind == "t1").map(_.dataAsCommentData))
  }

  //todo comments are filtering out "t3" kinds, which are selfposts and links
  def getRecentCommentsBySameAuthor(commentData: CommentData, limit: Int): Future[List[CommentData]] = {
    val response = apiWrapper.requestRecentCommentsForUser(commentData.author, limit)
    response.map(_.data.children.filter(_.kind == "t1").map(_.dataAsCommentData))
  }
}


class OAuthRedditService(override val apiWrapper: RedditOauth2ApiWrapper)(implicit system: ActorSystem, ec: ExecutionContext, mat: Materializer) extends RedditService(apiWrapper) {

  import RedditDataModel._

  def getSubscribedSubreddits()(implicit token: OAuth2BearerToken): List[SubredditData] = {
    val response = Await.result(apiWrapper.requestSubscribedSubreddits, Duration.Inf)
    //todo failure case
    response.data.children.map(_.dataAsSubredditData)
  }

  def oAuthUrl(authState: UUID, scope: List[String] = List("mysubreddits","history"), duration: String = "permanent"): String = {
    apiWrapper.requestAuthorizationUrl(authState, scope, duration)
  }

  def oAuthGetToken(code: String): Future[String] = {
    apiWrapper.requestAccessToken(code).map(_.access_token)
  }

} 
开发者ID:vikram-r,项目名称:subreddit-suggester,代码行数:57,代码来源:RedditService.scala


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