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

Scala JwtAlgorithm类代码示例

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

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



在下文中一共展示了JwtAlgorithm类的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: AuthenticatedRequest

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

import java.util.UUID
import javax.inject.Inject

import models.Account
import pdi.jwt.{JwtAlgorithm, JwtJson}
import play.api.libs.json.{JsError, JsSuccess, Json}
import play.api.mvc._
import repositories.AccountRepository
import utils.{Conf, Log}

import scala.concurrent.Future
import scala.util.{Failure, Success}

case class AuthenticatedRequest[A](account: Account, request: Request[A]) extends WrappedRequest[A](request)

class AuthenticationActionService @Inject()(conf: Conf, accountRepository: AccountRepository) extends Log {
  val key = conf.cryptoKey

  object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] {
    override def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
      val errorResponse = Json.obj("error" -> "Unauthorized")
      request.headers.get("Authorization")
      .orElse(request.getQueryString("token"))
      .orElse(request.cookies.get("token").map(_.value))
      .orElse(request.session.get("token")) match {
        case Some(token) =>
          logger.debug(s"${request.toString()} Authorization=$token")
          JwtJson.decodeJson(token, key, Seq(JwtAlgorithm.HS256)) match {
            case Success(json) =>
              (json \ "user_id").validate[UUID] match {
                case s: JsSuccess[UUID] =>
                  accountRepository.getByUUID(s.get) match {
                  case Some(user) =>
                    logger.debug(s"${request.toString()} user=$user")
                    block(AuthenticatedRequest(user, request))
                  case None =>
                    logger.error(s"Unauthorized: User not found with id=${s.get}")
                    Future.successful(Results.Unauthorized(errorResponse))
                  }
                case e: JsError =>
                  logger.error(s"Unauthorized: Jwt decode Json error $e")
                  Future.successful(Results.Unauthorized(errorResponse))
              }
            case Failure(e) =>
              logger.error(s"Unauthorized: Jwt decode Json error", e)
              Future.successful(Results.Unauthorized(errorResponse))
          }
        case None =>
          logger.error(s"Unauthorized: Missing token in Authorization header | cookies | session | query string")
          Future.successful(Results.Unauthorized(errorResponse))
      }
    }
  }
} 
开发者ID:Cumulus-Cloud,项目名称:cumulus,代码行数:57,代码来源:AuthenticationActionService.scala


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


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

//设置package包名称以及导入依赖的类
package io.digitalcat.publictransportation.services.identity.impl.util

import com.typesafe.config.ConfigFactory
import io.digitalcat.publictransportation.services.common.authentication.TokenContent
import pdi.jwt.{JwtAlgorithm, JwtClaim, JwtJson}
import play.api.libs.json.{Format, Json}

object JwtTokenUtil {
  val secret = ConfigFactory.load().getString("jwt.secret")
  val authExpiration = ConfigFactory.load().getInt("jwt.token.auth.expirationInSeconds")
  val refreshExpiration = ConfigFactory.load().getInt("jwt.token.refresh.expirationInSeconds")
  val algorithm = JwtAlgorithm.HS512

  def generateTokens(content: TokenContent)(implicit format: Format[TokenContent]): Token = {
    val authClaim = JwtClaim(Json.toJson(content).toString())
      .expiresIn(authExpiration)
      .issuedNow

    val refreshClaim = JwtClaim(Json.toJson(content.copy(isRefreshToken = true)).toString())
      .expiresIn(refreshExpiration)
      .issuedNow

    val authToken = JwtJson.encode(authClaim, secret, algorithm)
    val refreshToken = JwtJson.encode(refreshClaim, secret, algorithm)

    Token(
      authToken = authToken,
      refreshToken = Some(refreshToken)
    )
  }

  def generateAuthTokenOnly(content: TokenContent)(implicit format: Format[TokenContent]): Token = {
    val authClaim = JwtClaim(Json.toJson(content.copy(isRefreshToken = false)).toString())
      .expiresIn(authExpiration)
      .issuedNow

    val authToken = JwtJson.encode(authClaim, secret, algorithm)

    Token(
      authToken = authToken,
      None
    )
  }
}

case class Token(authToken: String, refreshToken: Option[String])
object Token {
  implicit val format: Format[Token] = Json.format
} 
开发者ID:dpalinic,项目名称:lagom-jwt-authentication,代码行数:50,代码来源:JwtTokenUtil.scala


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


示例8: UserService

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

import models.{UserRepository, User}
import javax.inject._
import scala.concurrent.Future
import play.api.Configuration
import play.Logger
import pdi.jwt.{JwtJson, JwtAlgorithm}

@Singleton
class UserService @Inject() (userRepo: UserRepository, configuration: Configuration) {
  def authenticate(name: String, password: String): Future[Option[User]] = {
    userRepo.authenticate(name, password)
  }

  def authenticate(token: String): Option[User] = {
    for {
      key <- configuration.getString("play.crypto.secret")
      decoded <- JwtJson.decodeJson(token, key, Seq(JwtAlgorithm.HmacSHA256)).toOption
      user <- (decoded \ "user").validate[User].asOpt
    } yield user
  }

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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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