Akka(42): Http:身份验证 - authentication, autorization and use of raw headers
当我们把Akka-http作为数据库数据交换工具时,数据是以Source[ROW,_]形式存放在Entity里的。很多时候除数据之外我们可能需要进行一些附加的信息传递如对数据的具体处理方式等。我们可以通过Akka-http的raw-header来实现附加自定义消息的传递,这项功能可以通过Akka-http提供的raw-header筛选功能来实现。在客户端我们把附加消息放在HttpRequest的raw header里,如下:
- import akka.http.scaladsl.model.headers._
- val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
- .addHeader(RawHeader("action","insert:county"))
在这里客户端注明上传数据应插入county表。服务端可以像下面这样获取这项信息:
- optionalHeaderValueByName("action") {
- case Some(action) =>
- entity(asSourceOf[County]) { source =>
- val futofNames: Future[List[String]] =
- source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
- complete(s"Received rows for $action")
- }
- case None => complete ("No action specified!")
- }
Akka-http通过Credential类的Directive提供了authentication和authorization。在客户端可以用下面的方法提供自己的用户身份信息:
- import akka.http.scaladsl.model.headers._
- val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
- .addHeader(RawHeader("action","insert:county"))
- .addCredentials(BasicHttpCredentials("john", "p4ssw0rd"))
服务端对客户端的身份验证处理方法如下:
- import akka.http.scaladsl.server.directives.Credentials
- def myUserPassAuthenticator(credentials: Credentials): Future[Option[User]] = {
- implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
- credentials match {
- case p @ Credentials.Provided(id) =>
- Future {
- // potentially
- if (p.verify("p4ssw0rd")) Some(User(id))
- else None
- }
- case _ => Future.successful(None)
- }
- }
- case class User(name: String)
- val validUsers = Set("john","peter","tiger","susan")
- def hasAdminPermissions(user: User): Future[Boolean] = {
- implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
- Future.successful(validUsers.contains(user.name))
- }
下面是Credential-Directive的使用方法:
- authenticateBasicAsync(realm = "secure site", userPassAuthenticator) { user =>
- authorizeAsync(_ => hasPermissions(user)) {
- withoutSizeLimit {
- handleExceptions(postExceptionHandler) {
- optionalHeaderValueByName("action") {
- case Some(action) =>
- entity(asSourceOf[County]) { source =>
- val futofNames: Future[List[String]] =
- source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
- complete(s"Received rows for $action sent from $user")
- }
- case None => complete(s"$user did not specify action for uploaded rows!")
- }
- }
- }
- }
- }
下面是本次讨论的示范代码:
客户端:
- import akka.actor._
- import akka.stream._
- import akka.stream.scaladsl._
- import akka.http.scaladsl.Http
- import scala.util._
- import akka._
- import akka.http.scaladsl.common._
- import spray.json.DefaultJsonProtocol
- import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
- import akka.http.scaladsl.common.EntityStreamingSupport
- import akka.http.scaladsl.model._
- import spray.json._
- trait MyFormats extends SprayJsonSupport with DefaultJsonProtocol
- object Converters extends MyFormats {
- case class County(id: Int, name: String)
- implicit val countyFormat = jsonFormat2(County)
- }
- object HttpClientDemo extends App {
- import Converters._
- implicit val sys = ActorSystem("ClientSys")
- implicit val mat = ActorMaterializer()
- implicit val ec = sys.dispatcher
- implicit val jsonStreamingSupport: JsonEntityStreamingSupport = EntityStreamingSupport.json()
- import akka.util.ByteString
- import akka.http.scaladsl.model.HttpEntity.limitableByteSource
- val source: Source[County,NotUsed] = Source( to ).map {i => County(i, s"广西壮族自治区地市县编号 #$i")}
- def countyToByteString(c: County) = {
- ByteString(c.toJson.toString)
- }
- val flowCountyToByteString : Flow[County,ByteString,NotUsed] = Flow.fromFunction(countyToByteString)
- val rowBytes = limitableByteSource(source via flowCountyToByteString)
- import akka.http.scaladsl.model.headers._
- val request = HttpRequest(HttpMethods.POST,uri = s"http://localhost:8011/rows")
- .addHeader(RawHeader("action","insert:county"))
- .addCredentials(BasicHttpCredentials("john", "p4ssw0rd"))
- val data = HttpEntity(
- ContentTypes.`application/json`,
- rowBytes
- )
- def uploadRows(request: HttpRequest, dataEntity: RequestEntity) = {
- val futResp = Http(sys).singleRequest(
- request.copy(entity = dataEntity)
- )
- futResp
- .andThen {
- case Success(r@HttpResponse(StatusCodes.OK, _, entity, _)) =>
- entity.dataBytes.map(_.utf8String).runForeach(println)
- case Success(r@HttpResponse(code, _, _, _)) =>
- println(s"Upload request failed, response code: $code")
- r.discardEntityBytes()
- case Success(_) => println("Unable to Upload file!")
- case Failure(err) => println(s"Upload failed: ${err.getMessage}")
- }
- }
- uploadRows(request,data)
- scala.io.StdIn.readLine()
- sys.terminate()
- }
服务端:
- import akka.actor._
- import akka.stream._
- import akka.stream.scaladsl._
- import akka.http.scaladsl.Http
- import akka._
- import akka.http.scaladsl.common._
- import spray.json.DefaultJsonProtocol
- import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
- import scala.concurrent._
- import akka.http.scaladsl.server._
- import akka.http.scaladsl.server.Directives._
- import akka.http.scaladsl.model._
- trait MyFormats extends SprayJsonSupport with DefaultJsonProtocol
- object Converters extends MyFormats {
- case class County(id: Int, name: String)
- val source: Source[County, NotUsed] = Source( to ).map { i => County(i, s"中国广东省地区编号 #$i") }
- implicit val countyFormat = jsonFormat2(County)
- }
- object HttpServerDemo extends App {
- import Converters._
- implicit val httpSys = ActorSystem("httpSystem")
- implicit val httpMat = ActorMaterializer()
- implicit val httpEC = httpSys.dispatcher
- implicit val jsonStreamingSupport = EntityStreamingSupport.json()
- .withParallelMarshalling(parallelism = , unordered = false)
- def postExceptionHandler: ExceptionHandler =
- ExceptionHandler {
- case _: RuntimeException =>
- extractRequest { req =>
- req.discardEntityBytes()
- complete((StatusCodes.InternalServerError.intValue, "Upload Failed!"))
- }
- }
- import akka.http.scaladsl.server.directives.Credentials
- def userPassAuthenticator(credentials: Credentials): Future[Option[User]] = {
- implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
- credentials match {
- case p @ Credentials.Provided(id) =>
- Future {
- // potentially
- if (p.verify("p4ssw0rd")) Some(User(id))
- else None
- }
- case _ => Future.successful(None)
- }
- }
- case class User(name: String)
- val validUsers = Set("john","peter","tiger","susan")
- def hasPermissions(user: User): Future[Boolean] = {
- implicit val blockingDispatcher = httpSys.dispatchers.lookup("akka-httpblocking-ops-dispatcher")
- Future.successful(validUsers.contains(user.name))
- }
- val route =
- path("rows") {
- get {
- complete {
- source
- }
- } ~
- post {
- authenticateBasicAsync(realm = "secure site", userPassAuthenticator) { user =>
- authorizeAsync(_ => hasPermissions(user)) {
- withoutSizeLimit {
- handleExceptions(postExceptionHandler) {
- optionalHeaderValueByName("action") {
- case Some(action) =>
- entity(asSourceOf[County]) { source =>
- val futofNames: Future[List[String]] =
- source.runFold(List[String](""))((acc, b) => acc ++ List(b.name))
- complete(s"Received rows for $action sent from $user")
- }
- case None => complete(s"$user did not specify action for uploaded rows!")
- }
- }
- }
- }
- }
- }
- }
- val (port, host) = (,"localhost")
- val bindingFuture = Http().bindAndHandle(route,host,port)
- println(s"Server running at $host $port. Press any key to exit ...")
- scala.io.StdIn.readLine()
- bindingFuture.flatMap(_.unbind())
- .onComplete(_ => httpSys.terminate())
- }
Akka(42): Http:身份验证 - authentication, autorization and use of raw headers的更多相关文章
- Akka(42): Http:身份验证 - authentication, authorization and use of raw headers
当我们把Akka-http作为数据库数据交换工具时,数据是以Source[ROW,_]形式存放在Entity里的.很多时候除数据之外我们可能需要进行一些附加的信息传递如对数据的具体处理方式等.我们可以 ...
- 也谈Asp.net 中的身份验证
钱李峰 的这篇博文<Asp.net中的认证与授权>已对Asp.net 中的身份验证进行了不错实践.而我这篇博文,是从初学者的角度补充了一些基础的概念,以便能有个清晰的认识. 一.配置安全身 ...
- .net core使用ocelot---第二篇 身份验证
简介原文链接 .net core使用ocelot---第一篇 简单使用 接上文,我将继续介绍使用asp.net core 创建API网关,主要介绍身份验证(authentication )相 ...
- 学学dotnet core中的身份验证和授权-1-概念
前言 身份验证: Authentication 授权: Authorization net core 中的身份验证和授权这两个部分,是相辅相成的.当初我在学在部分的时候,是看的 net core 官网 ...
- Angular 应用中的登陆与身份验证
Angular 经常会被用到后台和管理工具的开发,这两类都会需要对用户进行鉴权.而鉴权的第一步,就是进行身份验证.由于 Angular 是单页应用,会在一开始,就把大部分的资源加载到浏览器中,所以就更 ...
- 【记录】ASP.NET MVC 4/5 Authentication 身份验证无效
在 ASP.NET MVC 4/5 应用程序发布的时候,遇到一个问题,在本应用程序中进行身份验证是可以,但不能和其他"二级域名"共享,在其他应用程序身份验证,不能和本应用程序共享, ...
- SQL Server安全(2/11):身份验证(Authentication)
在保密你的服务器和数据,防备当前复杂的攻击,SQL Server有你需要的一切.但在你能有效使用这些安全功能前,你需要理解你面对的威胁和一些基本的安全概念.这篇文章提供了基础,因此你可以对SQL Se ...
- 发布Restful服务时出现IIS 指定了身份验证方案错误时的解决方案(IIS specified authentication schemes)
发布RESTful服务,当访问.svc文件时出现如下错误时: IIS 指定了身份验证方案“IntegratedWindowsAuthentication, Anonymous”,但绑定仅支持一种身份验 ...
- Zend Framework 2参考Zend\Authentication(摘要式身份验证)
Zend Framework 2参考Zend\Authentication(摘要式身份验证) 介绍 摘要式身份验证是HTTP身份验证的方法,提高了基本身份验证时提供的方式进行身份验证,而无需在网络上以 ...
随机推荐
- centos 源码安装python
一.准备环境 首先在官网下载想要的python对应版本http//www.python.org/downloads/source 下载tgz就可以了.文件有两种 1,Python-版本号.tgz(解压 ...
- Javaweb项目开发的前后端解耦的必要性
JavaWeb项目为何我们要放弃jsp?为何要前后端解耦?为何要动静分离? 使用jsp的痛点: 1.jsp上动态资源和静态资源全部耦合在一起,服务器压力大,因为服务器会收到各种静态资源的http请求, ...
- 用git上传本地文件到github
1.在自己的github账号下新建仓库--------得到github仓库地址 2.本地安装git---在将要克隆的文件夹下 右击点击Git Bash Here 3.输入命令 $ git clone ...
- CQRS微服务架构模式
什么是微服务? 这是维基百科里面的定义:“微服务是面向服务架构(SOA)架构风格的一种变体,它将应用程序构建为一系列松散耦合的服务.在微服务体系结构中,服务应该是细粒度的,协议应该是轻量级的.将应用 ...
- JS5模拟类
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- C#中结构体定义并转换字节数组
最近的项目在做socket通信报文解析的时候,用到了结构体与字节数组的转换:由于客户端采用C++开发,服务端采用C#开发,所以双方必须保证各自定义结构体成员类型和长度一致才能保证报文解析的正确性,这一 ...
- Cordova cannot add Android failed with exit code ENOENT
这可能是系统环境变量损坏了 解决方案:在系统变量path如果没用下面的变量就加上%SystemRoot%\system32; %SystemRoot%; %SystemRoot%\System32\W ...
- 将非常规Json字符串转换为常用的json对象
如下所示,这是一个已经转换为Json对象的非常规Json字符串,原来是一个Json类型的字符串,在转换为Json对象时,查询资料发现有两种转换法,.parse()和.eval()方法,但是前辈们都极其 ...
- Node.js初探之POST方式传输
小知识:POST比GET传输的数据量大很多 POST发数据--"分段" 实例: 准备一个form.html文件: <!DOCTYPE html> <html> ...
- python基础-------模块与包(一)
模块与包 Python中的py文件我们拿来调用的为之模块:主要有内置模块(Python解释器自带),第三方模块(别的开发者开发的),自定义模块. 目前我们学习的是内置模块与第三方模块. 通过impor ...