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

Scala Jwt类代码示例

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

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



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

示例1: IdJwtHandler

//设置package包名称以及导入依赖的类
package io.scalac.frees.login.handlers.id

import java.security.{PrivateKey, PublicKey}
import java.util.concurrent.TimeUnit

import cats.Id
import io.scalac.frees.login.algebras.{Claims, JwtService}
import io.scalac.frees.login.types.{JWT, UserId}
import pdi.jwt.{Jwt, JwtAlgorithm, JwtCirce, JwtClaim}

import scala.concurrent.duration.FiniteDuration
import scala.util.Try

class IdJwtHandler(
  pubKey: PublicKey,
  privKey: PrivateKey
) extends JwtService.Handler[Id] {
  val twoDays = FiniteDuration(2, TimeUnit.DAYS).toSeconds
  val algo = JwtAlgorithm.ES512

  override def issue(id: UserId): Id[JWT] = {

    val claim = JwtClaim()
      .about(id.toString)
      .issuedNow
      .expiresIn(twoDays)

    Jwt.encode(claim, privKey, algo)
  }

  override def validate(jwt: JWT): Id[Option[Claims]] = {
    JwtCirce.decode(jwt, pubKey, Seq(algo)).toOption.flatMap { c =>
      for {
        userId <- c.subject.flatMap(s => Try(s.toLong).toOption)
        expiration <- c.expiration.filter(_ > currentTimeSeconds)
        issuedAt <- c.issuedAt.filter(_ <= System.currentTimeMillis())
      } yield Claims(userId, issuedAt, expiration)
    }
  }

  private def currentTimeSeconds: Long = System.currentTimeMillis() / 1000

} 
开发者ID:LGLO,项目名称:freestyle-login,代码行数:44,代码来源:IdJwtHandler.scala


示例2: generateToken

//设置package包名称以及导入依赖的类
package services.cryptography

import java.io.File

import com.typesafe.config.ConfigFactory
import pdi.jwt.{Jwt, JwtAlgorithm}
import play.libs.Json

import scala.util.{Success, Try}


trait JwtTokenGeneratorServices {
  def generateToken(u : String) : String
  def verifyToken(token : String) : Try[(String,String,String)]
  def fetchPayload(token : String) : String
}

class JwtTokenGenerator extends JwtTokenGeneratorServices {

  val conf = ConfigFactory.parseFile(new File("conf/application.conf"))
  val secret = ConfigFactory.load(conf).getString("play.crypto.secret")

  override def generateToken(u : String): String = Jwt.encode(s"""{ "user" : $u }""", secret, JwtAlgorithm.HS256)
  override def verifyToken(token : String): Try[(String,String,String)] = Jwt.decodeRawAll(token, secret, Seq(JwtAlgorithm.HS256))

  override def fetchPayload(token: String): String = {
    val jwt = Jwt.decode(token, secret, Seq(JwtAlgorithm.HS256))
    jwt match {
      case Success(x) => Json.parse(x).get("user").asText
    }
  }
} 
开发者ID:mubeenahmed,项目名称:MeGuideApi,代码行数:33,代码来源:JwtTokenGeneratorServices.scala


示例3: verifyToken

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

import com.github.cupenya.microservices.sdk.logging.Logging
import com.typesafe.config.ConfigFactory
import pdi.jwt.{Jwt, JwtAlgorithm}

import scala.concurrent.{ExecutionContext, Future}
import spray.json._

trait TokenVerifier[T] {
  def verifyToken(token: String)(implicit ec: ExecutionContext): Future[T]
}

class JwtTokenVerifier extends TokenVerifier[AuthInfo] with DefaultJsonProtocol with Logging {

  implicit val authInfoFormat = jsonFormat5(AuthInfo)

  val config = ConfigFactory.load()

  override def verifyToken(token: String)(implicit ec: ExecutionContext): Future[AuthInfo] = Future {
    Jwt.decode(token, config.getString("authentication.secret"), Seq(JwtAlgorithm.HS256)).map { decodedJson =>
      log.debug(s"Decoded json token $decodedJson")
      decodedJson.parseJson.convertTo[AuthInfo]
    }.get
  }
} 
开发者ID:cupenya,项目名称:microservices-sdk,代码行数:27,代码来源:TokenVerifier.scala


示例4: AuthController

//设置package包名称以及导入依赖的类
package controllers

import javax.inject._

import pdi.jwt.{Jwt, JwtSession}
import play.api.libs.json.Json
import play.api.mvc.{Action, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import services.MongoAuthService

import scala.concurrent.Future


@Singleton
class AuthController @Inject()(val reactiveMongoApi: ReactiveMongoApi, val authService: MongoAuthService) extends Controller with MongoController with ReactiveMongoComponents {

  def get_token = Action.async(parse.json) { implicit request =>
    val emailOpt = (request.body \ "email").asOpt[String]
    val passwordOpt = (request.body \ "password").asOpt[String]
    (emailOpt, passwordOpt) match {
      case (Some(email), Some(password)) if !email.trim.isEmpty && !password.isEmpty =>
        for {
          idOpt <- authService.authenticate(email, password)
        } yield {
          idOpt.map {
            id =>
              var session = JwtSession()
              val user = Json.obj("user" -> Json.obj("_id" -> id, "email" -> email))
              session = session + user
              val token = session.serialize
              Ok(Json.obj("token" -> token))
          }.getOrElse(Ok(Json.obj()))
        }
      case _ => Future.successful(Ok(Json.obj()))
    }
  }

} 
开发者ID:sdor,项目名称:labnotes-server,代码行数:40,代码来源:AuthController.scala


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


示例6: SessionManager

//设置package包名称以及导入依赖的类
package nl.tradecloud.common.utils.session

import com.typesafe.config.Config
import net.ceedubs.ficus.Ficus._
import net.ceedubs.ficus.readers.ArbitraryTypeReader._
import org.json4s.Formats
import org.json4s.jackson.Serialization
import pdi.jwt.algorithms.JwtHmacAlgorithm
import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim}

import scala.util.Try

class SessionManager[T <: AnyRef](config: Config)(implicit val formats: Formats, mf: Manifest[T]) {
  private[this] final val sessionConfig: SessionConfig = config.as[SessionConfig]("akka.http.session")
  private[this] final val algorithm: JwtHmacAlgorithm = JwtAlgorithm.HS256

  lazy val setHeaderName: String = sessionConfig.setHeaderName.getOrElse("Set-Authorization")
  lazy val headerName: String = sessionConfig.headerName.getOrElse("Authorization")

  def encode(sessionData: T): String = {
    val claim: JwtClaim = JwtClaim(
      content = Serialization.write[T](sessionData)
    )
    Jwt.encode(
      sessionConfig.headerTtl
        .map(ttl => claim.issuedNow.expiresIn(ttl))
        .getOrElse(claim),
      sessionConfig.secret,
      algorithm
    )
  }

  def decode(token: String): Try[T] = {
    Jwt.decode(
      token,
      sessionConfig.secret,
      Seq(algorithm)
    ).flatMap(t => Try(Serialization.read[T](t)))
  }

} 
开发者ID:tradecloud,项目名称:tradecloud-microservices-demo,代码行数:42,代码来源:SessionManager.scala


示例7: UserContext

//设置package包名称以及导入依赖的类
package mu.node.echod.models

import java.security.{PrivateKey, PublicKey}
import java.util.Calendar

import mu.node.echod.util.KeyUtils
import pdi.jwt.Jwt
import play.api.libs.json.Json

import scala.util.Try

case class UserContext(userId: String) extends KeyUtils {

  def toJwt(expiryMillis: Long, jwtSigningKey: PrivateKey): String = {
    val json =
      s"""{
         |  "sub": "$userId",
         |  "exp": $expiryMillis
         |}
         |""".stripMargin
    Jwt.encode(json, jwtSigningKey, jwtDsa)
  }
}

object UserContext extends KeyUtils {
  def fromJwt(jwt: String, jwtVerificationKey: PublicKey): Option[UserContext] = {
    Jwt
      .decode(jwt, jwtVerificationKey, Seq(jwtDsa))
      .flatMap(payload => Try(Json.parse(payload)))
      .toOption
      .filter(json => (json \ "exp").asOpt[Long].exists(notExpired))
      .flatMap(json => (json \ "sub").asOpt[String].map(UserContext(_)))
  }

  private def notExpired(expiryMillis: Long): Boolean =
    expiryMillis > Calendar.getInstance().getTimeInMillis
} 
开发者ID:vyshane,项目名称:grpc-scala-microservice-kit,代码行数:38,代码来源:UserContext.scala


示例8: UserContextSpec

//设置package包名称以及导入依赖的类
package mu.node.echod

import java.util.Calendar

import mu.node.echod.models.UserContext
import mu.node.echod.util.KeyUtils
import pdi.jwt.Jwt

import scala.concurrent.duration._

class UserContextSpec extends BaseSpec with KeyUtils {
  val jwtSigningKey = loadPkcs8PrivateKey(
    pathForTestResourcePath(config.getString("jwt.signing-key")))

  "The UserContext companion object" when {

    val userId = "8d5921be-8f85-11e6-ae22-56b6b6499611"
    val futureExpiry = Calendar.getInstance().getTimeInMillis + Duration(5, MINUTES).toMillis
    val validClaim =
      s"""|{
          |  "sub": "$userId",
          |  "exp": $futureExpiry
          |}""".stripMargin

    "asked to create a UserContext from a valid, signed JWT" should {
      "return the UserContext" in {
        val validJwt = Jwt.encode(validClaim, jwtSigningKey, jwtDsa)
        UserContext.fromJwt(validJwt, jwtVerificationKey) shouldEqual Some(UserContext(userId))
      }
    }

    "asked to create UserContext from an unsigned JWT" should {
      "return None" in {
        val unsignedJwt = Jwt.encode(validClaim)
        UserContext.fromJwt(unsignedJwt, jwtVerificationKey) shouldEqual None
      }
    }

    "asked to create UserContext from a JWT with an invalid claim" should {
      "return None" in {
        val invalidClaim = s"""{ "unknownField": "value" }"""
        val invalidJwt = Jwt.encode(invalidClaim, jwtSigningKey, jwtDsa)
        UserContext.fromJwt(invalidJwt, jwtVerificationKey) shouldEqual None
      }
    }

    "asked to create UserContext from a JWT with an invalid payload" should {
      "return None" in {
        val invalidPayload = "malformed JSON"
        val invalidJwt = Jwt.encode(invalidPayload, jwtSigningKey, jwtDsa)
        UserContext.fromJwt(invalidJwt, jwtVerificationKey) shouldEqual None
      }
    }
  }
} 
开发者ID:vyshane,项目名称:grpc-scala-microservice-kit,代码行数:56,代码来源:UserContextSpec.scala


示例9: verifyToken

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

import com.github.cupenya.hello.{ Config, Logging }
import pdi.jwt.{ Jwt, JwtAlgorithm }

import scala.concurrent.{ ExecutionContext, Future }
import spray.json._

trait TokenVerifier[T] {
  def verifyToken(token: String)(implicit ec: ExecutionContext): Future[T]
}

class JwtTokenVerifier extends TokenVerifier[AuthInfo] with DefaultJsonProtocol with Logging {

  implicit val authInfoFormat = jsonFormat5(AuthInfo)

  override def verifyToken(token: String)(implicit ec: ExecutionContext): Future[AuthInfo] = Future {
    Jwt.decode(token, Config.authentication.secret, Seq(JwtAlgorithm.HS256)).map { decodedJson =>
      log.debug(s"Decoded json token $decodedJson")
      decodedJson.parseJson.convertTo[AuthInfo]
    }.get
  }
} 
开发者ID:cupenya,项目名称:hello-world-microservice,代码行数:24,代码来源:TokenVerifier.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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