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

Scala Credentials类代码示例

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

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



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

示例1: NoAuthority

//设置package包名称以及导入依赖的类
package co.horn.alkes.auth
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.directives.Credentials

import scala.concurrent.Future
import scala.util.Random


class NoAuthority extends Authority {
  lazy val anonymous = new Random(1337L)

  def ping: Future[HttpResponse] = Future.successful(HttpResponse(StatusCodes.OK))

  def channelAccess(credentials: Credentials, channel_uuid: String): Future[Option[Long]] = {
    Future.successful(Some(anonymous.nextLong))
  }

  def overlordAccess(credentials: Credentials): Future[Option[Long]] = {
    Future.successful(Some(anonymous.nextLong))
  }
} 
开发者ID:DalenWBrauner,项目名称:Alkes-Prototype,代码行数:22,代码来源:NoAuthority.scala


示例2: Authenticators

//设置package包名称以及导入依赖的类
package org.nephtys.keepaseat.internal.configs

import akka.http.scaladsl.server.{Directive, Route}
import akka.http.scaladsl.server.Directives.authenticateBasic
import akka.http.scaladsl.server.directives.Credentials


object Authenticators {

  def normalUserOrSuperuserAuthenticator(config : PasswordConfig)(credentials : Credentials) : Option[String] = {
    credentials match {
      case p @ Credentials.Provided(id) if (id == config.normalUser.username && p.verify(config.normalUser.password)
        ) || (id == config.superUser.username && p.verify(config.superUser.password)
        ) => Some(id)
      case _ => None
    }
  }

  def onlySuperuserAuthenticator(config : PasswordConfig)(credentials : Credentials) : Option[String] = {
    credentials match {
      case p @ Credentials.Provided(id) if id == config.superUser.username && p.verify(config.superUser.password) => Some(id)
      case _ => None
    }
  }

  def BasicAuthOrPass(passwordConfig : PasswordConfig, onlySuperusers : Boolean)(routeInner : () => Route) : Route = {
    if (passwordConfig.hasPasswords) {
      authenticateBasic(passwordConfig.realmForCredentials, if(onlySuperusers) onlySuperuserAuthenticator(passwordConfig) else normalUserOrSuperuserAuthenticator
      (passwordConfig)) {
        username => routeInner.apply()
      }
    } else {
      routeInner.apply()
    }

  }
} 
开发者ID:n3phtys,项目名称:keep-a-seat,代码行数:38,代码来源:Authenticators.scala


示例3: createToken

//设置package包名称以及导入依赖的类
package shine.st.blog.handler

import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.Credentials
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}
import shine.st.blog.api.tokenKey
import shine.st.blog.dao.ManagerCollectionDao
import shine.st.blog.protocol.document.Manager
import shine.st.blog.protocol.input.TokenHeader
import spray.json.JsonParser


trait AuthenticationHandler {


  def createToken(secretKey: String, id: String): String = {
    val jwtClaim = JwtClaim(s"""{"id": "$id"}""").issuedNow.expiresIn(60 * 60 * 6)
    Jwt.encode(jwtClaim, tokenKey, JwtAlgorithm.HS256)
  }


  def authenticator(key: String): Credentials => Option[Manager] =
    credentials =>
      credentials match {
        case [email protected](token) =>
          Jwt.validate(token, key, Seq(JwtAlgorithm.HS256))
          val res0 = Jwt.decodeRaw(token, key, Seq(JwtAlgorithm.HS256))

          val json = JsonParser(res0.toOption.get)
          val tokenHeader = json.convertTo[TokenHeader]
          ManagerCollectionDao.findById(tokenHeader.id)

        case _ => None
      }


  def authenticate(tokenKey: String) =
    authenticateOAuth2("", authenticator(tokenKey))
} 
开发者ID:shine-st,项目名称:blog-akka,代码行数:40,代码来源:AuthenticationHandler.scala


示例4: SimpleAuthenticator

//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.ui.security

import java.io.File

import akka.http.scaladsl.server.directives.Credentials.Provided
import akka.http.scaladsl.server.directives.{Credentials, SecurityDirectives}
import com.typesafe.config.ConfigFactory
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import pl.touk.nussknacker.ui.security.Permission.Permission
import net.ceedubs.ficus.readers.EnumerationReader._

class SimpleAuthenticator(path: String) extends SecurityDirectives.Authenticator[LoggedUser] {

  //TODO: config reload
  val users = prepareUsers()

  def prepareUsers() : Map[String, LoggedUser] = {
    val config = ConfigFactory.parseFile(new File(path))
    config.as[List[LoggedUser]]("users").map(u => u.id -> u).toMap
  }

  override def apply(credentials: Credentials) = credentials match {
    case [email protected](id) => users.get(id).filter(u => d.verify(u.password))
    case _ => None
  }
}

case class LoggedUser(id: String, password: String, permissions: List[Permission],
                      categories: List[String]) {
  def hasPermission(permission: Permission) = {
    permissions.contains(permission) || isAdmin
  }

  def isAdmin = permissions.contains(Permission.Admin)
}

object Permission extends Enumeration {
  type Permission = Value
  val Read, Write, Deploy, Admin = Value
} 
开发者ID:TouK,项目名称:nussknacker,代码行数:42,代码来源:SimpleAuthenticator.scala


示例5: exceptionHandler

//设置package包名称以及导入依赖的类
package com.wlangiewicz.workouttracker.api

import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.directives.Credentials
import com.wlangiewicz.workouttracker.domain.{ApiKey, User}

import scala.concurrent.ExecutionContextExecutor

trait Api extends RouteConcatenation with UserApi with WorkoutApi with ReportApi {
  implicit val system: ActorSystem

  implicit def exceptionHandler: ExceptionHandler =
    ExceptionHandler {
      case _: ApiException =>
        extractUri { uri =>
          complete(HttpResponse(BadRequest, entity = "invalid request"))
        }
    }

  val routes =
    Route.seal {
      userApiRoutes ~ workoutApiRoutes ~ reportApiRoutes
    }

  implicit def executor: ExecutionContextExecutor

  def apiAuthentication(credentials: Credentials): Option[User] =
    credentials match {
      case p @ Credentials.Provided(id) => userDao.findByApiKey(ApiKey(id))
      case Credentials.Missing          => None
      case _                            => None
    }

}

class ApiException(val message: String) extends RuntimeException(message) 
开发者ID:wlk,项目名称:workout-tracker-akka-http,代码行数:41,代码来源:Api.scala


示例6: UniqueUsernameAuthenticator

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

import akka.actor.ActorSystem
import akka.event.{LogSource, Logging}
import akka.http.scaladsl.server.directives.Credentials
import akka.http.scaladsl.server.directives.Credentials.{Missing, Provided}


class UniqueUsernameAuthenticator(actorSystem: ActorSystem) {

  private var usernames: Set[String] = Set.empty

  val log = Logging.getLogger(actorSystem, this)

  def authenticate(creds: Credentials): Option[String] = {
    log.debug(s"Client trying to connect with credentials: $creds")
    creds match {
      case Provided(identifier) =>
        if (usernames.contains(identifier)) {
          log.warning(s"Rejecting user $identifier because of duplicated username")
          Option.empty
        }
        else {
          usernames = usernames + identifier
          Option(identifier)
        }
      case Missing =>
        log.warning(s"Rejecting connection because of missing credentials")
        Option.empty
    }
  }
}

object UniqueUsernameAuthenticator {
  def apply(actorSystem: ActorSystem): UniqueUsernameAuthenticator = new UniqueUsernameAuthenticator(actorSystem)
} 
开发者ID:rbraeunlich,项目名称:formic,代码行数:37,代码来源:UniqueUsernameAuthenticator.scala


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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala KillSwitches类代码示例发布时间:2022-05-23
下一篇:
Scala DecoderFactory类代码示例发布时间: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