本文整理汇总了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))))
}
}
}
}
}
示例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
}
}
示例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]
}
}
}
}
示例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)
}
}
示例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)
}
示例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)
}
示例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)
}
示例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
}
}
}