• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala BasicHttpCredentials类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: AuthenticationRoute

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

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.{Directives, Route}
import core.authentication.AuthenticationService
import core.entities.UserSecret
import restapi.http.JsonSupport
import restapi.http.routes.support._

import scala.concurrent.{ExecutionContext, Future}

class AuthenticationRoute(authService: AuthenticationService)(implicit ec: ExecutionContext, ac: ApiContext)
    extends Directives with SecuredAccessSupport with ContentExtractionSupport with JsonSupport {

  val route: Route =
    pathPrefix("auth") {
      path("signIn") {
        post {
          extractClientInfo { clientInfo =>
            extractCredentials {
              case Some(BasicHttpCredentials(username, password)) =>
                complete(Future(authService.signIn(username, UserSecret(password))))
              case _ => complete(StatusCodes.Unauthorized)
            }
          }
        }
      } ~
        path("signUp") {
          post {
            extractClientInfo { clientInfo =>
              extractCredentials {
                case Some(BasicHttpCredentials(username, password)) =>
                  complete(Future(authService.signUp(username, UserSecret(password))))
                case _ => complete(StatusCodes.Unauthorized)
              }
            }
          }
        } ~
        path("signOut") {
          securedAccess { ctx =>
            post {
              Future(authService.signOut(ctx.userId))
              complete(StatusCodes.Accepted)
            }
          }
        }
    } ~
      path("credentials") {
        securedAccess { ctx =>
          patch {
            entity(as[String]) { password =>
              complete(Future(authService.updateCredentials(ctx.userId, UserSecret(password))))
            }
          }
        }
      }
} 
开发者ID:lymr,项目名称:fun-chat,代码行数:59,代码来源:AuthenticationRoute.scala


示例2: TokenAuthenticationFailedRejection

//设置package包名称以及导入依赖的类
package com.flipkart.connekt.receptors.directives

import akka.http.scaladsl.model.HttpHeader
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.AuthenticationFailedRejection.{CredentialsMissing, CredentialsRejected}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.directives.{BasicDirectives, RouteDirectives}
import com.flipkart.connekt.commons.entities.AppUser
import com.flipkart.connekt.commons.factories.{ConnektLogger, LogFile}
import com.flipkart.connekt.commons.metrics.Instrumented
import com.flipkart.connekt.receptors.service.AuthenticationService

trait AuthenticationDirectives extends HeaderDirectives with Instrumented{

  case class TokenAuthenticationFailedRejection(message: String) extends Rejection

  val X_API_KEY_HEADER = "x-api-key"
  val X_SECURE_CODE_HEADER = "x-secure-code"
  val AUTHORIZATION_HEADER = "Authorization"

  def authenticate: Directive1[AppUser] = {
    BasicDirectives.extract[Seq[HttpHeader]](_.request.headers) flatMap { headers =>
      getHeader(X_API_KEY_HEADER, headers).orElse{
        //try basic auth if available
        getHeader(AUTHORIZATION_HEADER, headers).filter(_.startsWith("Basic")).map { authHeader =>
          BasicHttpCredentials(authHeader.substring(6).trim).password
        }
      } match {
        case Some(apiKey) if apiKey.nonEmpty =>
          AuthenticationService.authenticateKey(apiKey) match {
            case Some(user) =>
              meter(s"authenticate.${user.userId}").mark()
              provide(user)
            case None =>
              ConnektLogger(LogFile.SERVICE).warn(s"authentication failure for apiKey: [$apiKey]")
              RouteDirectives.reject(AuthenticationFailedRejection(CredentialsRejected, null))
          }
        case _ =>
          RouteDirectives.reject(AuthenticationFailedRejection(CredentialsMissing, null))
      }
    }
  }

  def verifySecureCode(secretFragments: String*): Directive0 = {
    BasicDirectives.pass
    
  }

} 
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:51,代码来源:AuthenticationDirectives.scala


示例3: NetworkRouteSpec

//设置package包名称以及导入依赖的类
package de.tu_berlin.formic.example

import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.AuthenticationFailedRejection
import akka.http.scaladsl.testkit.{ScalatestRouteTest, WSProbe}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink, Source}
import org.scalatest.{BeforeAndAfterAll, Matchers, WordSpecLike}

class NetworkRouteSpec extends WordSpecLike
  with ScalatestRouteTest
  with Matchers
  with BeforeAndAfterAll{

  override def afterAll(): Unit = {
    super.afterAll()
  }

  "Network route" must {
    "reject users without authentification" in {
      implicit val materializer = ActorMaterializer()
      val probe = WSProbe()
      val route = new NetworkRoute()(system).route((_) => Flow.fromSinkAndSource(Sink.ignore, Source.empty))

      WS("/formic", probe.flow) ~> route ~> check {
        rejection shouldBe a[AuthenticationFailedRejection]
      }
    }

    "accept users with unique username independent of password" in {
      implicit val materializer = ActorMaterializer()
      val probe = WSProbe()
      val route = new NetworkRoute()(system).route((_) => Flow.fromSinkAndSource(Sink.ignore, Source.empty))

      WS("/formic", probe.flow).addCredentials(BasicHttpCredentials("NetworkRoute", "")) ~> route ~> check {
        isWebSocketUpgrade should be(true)
        status should be(StatusCodes.SwitchingProtocols)
      }
    }

    "reject users with duplicate username" in {
      implicit val materializer = ActorMaterializer()
      val probe = WSProbe()
      val probe2 = WSProbe()
      val route = new NetworkRoute()(system).route((_) => Flow.fromSinkAndSource(Sink.ignore, Source.empty))

      WS("/formic", probe.flow).addCredentials(BasicHttpCredentials("NetworkRoute2", "")) ~> route ~> check {
        isWebSocketUpgrade should be(true)
        status should be(StatusCodes.SwitchingProtocols)
      }

      WS("/formic", probe2.flow).addCredentials(BasicHttpCredentials("NetworkRoute2", "")) ~> route ~> check {
        rejection shouldBe a[AuthenticationFailedRejection]
      }
    }
  }
} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:59,代码来源:NetworkRouteSpec.scala


示例4: UniqueUsernameAuthenticatorSpec

//设置package包名称以及导入依赖的类
package de.tu_berlin.formic.example

import akka.actor.ActorSystem
import akka.http.scaladsl.model.headers.BasicHttpCredentials
import akka.http.scaladsl.server.directives.Credentials
import akka.testkit.TestKit
import org.scalatest.{BeforeAndAfterAll, FlatSpec, FlatSpecLike, Matchers}


class UniqueUsernameAuthenticatorSpec extends TestKit(ActorSystem("UniqueUsernameAuthenticatorSpec")) with FlatSpecLike with Matchers with BeforeAndAfterAll{

  "UniqueUserNameAuthenticator" should "accept new usernames" in {
    val authenticator = UniqueUsernameAuthenticator(system)
    val username = "UniqueUserNameAuthenticator"
    val auth = authenticator.authenticate(Credentials(Option(BasicHttpCredentials(username, ""))))
    val username2 = "UniqueUserNameAuthenticator1"
    val auth2 = authenticator.authenticate(Credentials(Option(BasicHttpCredentials(username2, ""))))
    val username3 = "UniqueUserNameAuthenticator2"
    val auth3 = authenticator.authenticate(Credentials(Option(BasicHttpCredentials(username3, ""))))

    auth should equal(Option(username))
    auth2 should equal(Option(username2))
    auth3 should equal(Option(username3))
  }

  it should "reject missing credentials" in {
    val authenticator = UniqueUsernameAuthenticator(system)
    val auth = authenticator.authenticate(Credentials(Option.empty))

    auth should equal(None)
  }
  it should "reject duplicate usernames" in {
    val authenticator = UniqueUsernameAuthenticator(system)
    val username = "duplicate"
    authenticator.authenticate(Credentials(Option(BasicHttpCredentials(username, ""))))
    val auth = authenticator.authenticate(Credentials(Option(BasicHttpCredentials(username, ""))))

    auth should equal(None)
  }

} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:42,代码来源:UniqueUsernameAuthenticatorSpec.scala


示例5: AuthService

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

import akka.http.scaladsl.model.headers.{BasicHttpCredentials, HttpCredentials}
import com.github.t3hnar.bcrypt._
import com.vitold.mauth.model.UserSession

import scala.concurrent.{ExecutionContext, Future}

class AuthService(
                   val sessionService: SessionService,
                   val userDao: UserDao
                 )(
                   implicit val ec: ExecutionContext
                 ) {

  def checkCredentials(credentials: Option[HttpCredentials]): Future[Option[UserSession]] = {
    credentials match {
      case Some(BasicHttpCredentials(login, password)) =>
        userDao.getUser(login).flatMap {
          case Some(user) if password.isBcrypted(user.password) =>
            sessionService.createSession(user)
          case _ =>
            Future.successful(None)
        }
      case _ =>
        Future.successful(None)
    }
  }

  def getSession(token: String) = sessionService.getSession(token)

} 
开发者ID:vitold,项目名称:mauth,代码行数:33,代码来源:AuthService.scala


示例6: customAuthenticateAsync

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

import akka.http.scaladsl.model.headers.{BasicHttpCredentials, HttpChallenges, HttpCredentials}
import akka.http.scaladsl.server.directives.{AuthenticationDirective, AuthenticationResult}
import akka.http.scaladsl.server.directives.Credentials.{Missing, Provided}
import akka.http.scaladsl.server.Directives._
import com.vitold.mauth.model.UserSession

import scala.concurrent.{ExecutionContext, Future}

trait Authentication {

  val authService: AuthService

  implicit val ec: ExecutionContext

  val realm: String

  private val oAuth2Authenticator: AsyncAuthenticator[UserSession] = {
    case Provided(token) =>
      authService.getSession(token)
    case Missing =>
      Future.successful(None)
  }

  type CustomAuthenticator[T] = Option[HttpCredentials] => Future[Option[T]]

  def customAuthenticateAsync[T](authenticator: CustomAuthenticator[T]): AuthenticationDirective[T] = {
    authenticateOrRejectWithChallenge[BasicHttpCredentials, T] { cred ?
      authenticator(cred).map {
        case Some(t) => AuthenticationResult.success(t)
        case None => AuthenticationResult.failWithChallenge(HttpChallenges.oAuth2(realm))
      }
    }
  }

  val basicAuth = customAuthenticateAsync(authService.checkCredentials)

  val oAuth = authenticateOAuth2Async(realm, oAuth2Authenticator)

} 
开发者ID:vitold,项目名称:mauth,代码行数:42,代码来源:Authentication.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.BasicHttpCredentials类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala EitherValues类代码示例发布时间:2022-05-23
下一篇:
Scala MemberEvent类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap