- 浏览: 2551766 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
Play framework and Authorization
Recently, I need to write a authorization solution for play framework. From my understanding, it is just a filter to protect the resources of all my actions in controllers.
I have done this for Spary framework. This time, we are facing play framework. It takes me sometime to figure this out.
First of all, I am using play framework 2.4.3 version.
I am using configuration file, but actually we should use Redis or other storage. But I only want to show how the filter works among the actions and controllers.
apigateway {
mapping=[
{ "key1" : "campaignId1" }
{ "key1" : "campaignId2" }
]
}
Here is how I read this configuration map.
val api_gateway_mapping: Map[String, Seq[String]]= {
val list:Iterable[ConfigObject] = config.getObjectList("apigateway.mapping").asScala
val result = (
for {
item:ConfigObject <- list
entry : Entry[String, ConfigValue] <- item.entrySet().asScala
key = entry.getKey
value = entry.getValue.unwrapped().toString
} yield (key, value)).groupBy(record => record._1 ) map { item =>
item._1 -> {
item._2.toSeq map { value =>
value._2
}
}
}
result
}
2 Important models
package com.sillycat.services.auth
import play.api.mvc.WrappedRequest
class ResourceRequest[A](val campaigns: Seq[String], val campaignID:String, request: TokenRequest[A]) extends WrappedRequest[A](request) {
def token = request.token
}
package com.sillycat.services.auth
import play.api.mvc._
class TokenRequest[A](val token: Option[String], request: Request[A]) extends WrappedRequest[A](request)
These requests are hosting more parameters, like token, campaignID, resources and etc.
Actions to Auth
what we will do in these actions, first, get the token from headers ——> fetch the mapping based on the token ——> get the resources from that request ——> match the mapping with the resources from request
#1 Get token from Headers
package com.sillycat.services.auth
import com.sillycat.utils.IncludeLogger
import play.api.mvc.{Request, ActionTransformer, ActionBuilder}
import scala.concurrent.Future
object TokenFetchAction
extends ActionBuilder[TokenRequest]
with ActionTransformer[Request, TokenRequest]
with IncludeLogger
{
def transform[A](request: Request[A]) = Future.successful {
val xToken = request.headers.get("x-api-key")
logger.trace("TokenFetchAction system gets token = " + xToken)
new TokenRequest(xToken, request)
}
}
#2 Fetch the Mapping
package com.sillycat.services.auth
object AuthorizeService
extends IncludeAuthConfig
{
/**
* no guava cache, no expire time, this is a just temperary solution
*/
val memoryCache:Map[String, Seq[String]] = api_gateway_mapping
def getResourceMappingByToken(xToken:String):Option[Seq[String]] = {
val resources = memoryCache.get(xToken)
resources
}
}
#3 Get resources from requests
package com.sillycat.services.auth
import com.sillycat.utils.IncludeLogger
import play.api.mvc.{Results, ActionRefiner}
import scala.concurrent.Future
trait IncludeAuthService
extends IncludeLogger
{
def ResourceFetchAction(campaignID:String) = new ActionRefiner[TokenRequest, ResourceRequest] {
def refine[A](request: TokenRequest[A]) = Future.successful {
val xTokenOpt = request.token
logger.trace("ResourceFetchAction get xTokenOpt = " + xTokenOpt)
xTokenOpt match {
case Some(xToken) => {
logger.trace("ResourceFetchAction get xToken = " + xToken)
val resourceOpt = AuthorizeService.getResourceMappingByToken(xToken)
resourceOpt.map{ resources =>
logger.trace("ResourceFetchAction get resources mapping = " + resources)
logger.trace("ResourceFetchAction get campaignID = " + campaignID)
new ResourceRequest(resources, campaignID, request)
}.toRight{
logger.error("ResourceFetchAction empty resources mapping data resourceOpt = " + resourceOpt)
Results.Unauthorized
}
}
case _ => {
logger.error("System does not get x-api-key, bad request.")
Left(Results.Unauthorized)
}
}
}
}
}
#4 Match the Mapping with resources
package com.sillycat.services.auth
import com.sillycat.utils.IncludeLogger
import play.api.mvc.{Results, ActionFilter}
import scala.concurrent.Future
object AuthCampaignCheckAction
extends ActionFilter[ResourceRequest]
with IncludeLogger
{
def filter[A](request: ResourceRequest[A]) = Future.successful {
val campaignID = request.campaignID
val resources = request.campaigns
logger.trace("AuthCampaignCheckAction campaignID = " + campaignID)
logger.trace("AuthCampaignCheckAction resources = " + resources)
if (resources.contains(campaignID)){
logger.trace("AuthCampaignCheckAction, You are authorized!")
None
} else{
logger.warn("AuthCampaignCheckAction, Unauthorized!")
Some(Results.Unauthorized)
}
}
}
After that, when we wants to use them in the Controller.
…snip...
with IncludeAuthService
..snip...
def addJob(
@ApiParam(name="campaignID",value="campaign ID",defaultValue=“xxxxx",required=true,allowMultiple=false)
@PathParam("campaignID")
campaignID:String
) = (TokenFetchAction andThen ResourceFetchAction(campaignID) andThen AuthCampaignCheckAction)(BodyParsers.parse.json) { implicit request =>
…snip...
References:
https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition
http://stackoverflow.com/questions/19868153/authorisation-check-in-controller-scala-play
Recently, I need to write a authorization solution for play framework. From my understanding, it is just a filter to protect the resources of all my actions in controllers.
I have done this for Spary framework. This time, we are facing play framework. It takes me sometime to figure this out.
First of all, I am using play framework 2.4.3 version.
I am using configuration file, but actually we should use Redis or other storage. But I only want to show how the filter works among the actions and controllers.
apigateway {
mapping=[
{ "key1" : "campaignId1" }
{ "key1" : "campaignId2" }
]
}
Here is how I read this configuration map.
val api_gateway_mapping: Map[String, Seq[String]]= {
val list:Iterable[ConfigObject] = config.getObjectList("apigateway.mapping").asScala
val result = (
for {
item:ConfigObject <- list
entry : Entry[String, ConfigValue] <- item.entrySet().asScala
key = entry.getKey
value = entry.getValue.unwrapped().toString
} yield (key, value)).groupBy(record => record._1 ) map { item =>
item._1 -> {
item._2.toSeq map { value =>
value._2
}
}
}
result
}
2 Important models
package com.sillycat.services.auth
import play.api.mvc.WrappedRequest
class ResourceRequest[A](val campaigns: Seq[String], val campaignID:String, request: TokenRequest[A]) extends WrappedRequest[A](request) {
def token = request.token
}
package com.sillycat.services.auth
import play.api.mvc._
class TokenRequest[A](val token: Option[String], request: Request[A]) extends WrappedRequest[A](request)
These requests are hosting more parameters, like token, campaignID, resources and etc.
Actions to Auth
what we will do in these actions, first, get the token from headers ——> fetch the mapping based on the token ——> get the resources from that request ——> match the mapping with the resources from request
#1 Get token from Headers
package com.sillycat.services.auth
import com.sillycat.utils.IncludeLogger
import play.api.mvc.{Request, ActionTransformer, ActionBuilder}
import scala.concurrent.Future
object TokenFetchAction
extends ActionBuilder[TokenRequest]
with ActionTransformer[Request, TokenRequest]
with IncludeLogger
{
def transform[A](request: Request[A]) = Future.successful {
val xToken = request.headers.get("x-api-key")
logger.trace("TokenFetchAction system gets token = " + xToken)
new TokenRequest(xToken, request)
}
}
#2 Fetch the Mapping
package com.sillycat.services.auth
object AuthorizeService
extends IncludeAuthConfig
{
/**
* no guava cache, no expire time, this is a just temperary solution
*/
val memoryCache:Map[String, Seq[String]] = api_gateway_mapping
def getResourceMappingByToken(xToken:String):Option[Seq[String]] = {
val resources = memoryCache.get(xToken)
resources
}
}
#3 Get resources from requests
package com.sillycat.services.auth
import com.sillycat.utils.IncludeLogger
import play.api.mvc.{Results, ActionRefiner}
import scala.concurrent.Future
trait IncludeAuthService
extends IncludeLogger
{
def ResourceFetchAction(campaignID:String) = new ActionRefiner[TokenRequest, ResourceRequest] {
def refine[A](request: TokenRequest[A]) = Future.successful {
val xTokenOpt = request.token
logger.trace("ResourceFetchAction get xTokenOpt = " + xTokenOpt)
xTokenOpt match {
case Some(xToken) => {
logger.trace("ResourceFetchAction get xToken = " + xToken)
val resourceOpt = AuthorizeService.getResourceMappingByToken(xToken)
resourceOpt.map{ resources =>
logger.trace("ResourceFetchAction get resources mapping = " + resources)
logger.trace("ResourceFetchAction get campaignID = " + campaignID)
new ResourceRequest(resources, campaignID, request)
}.toRight{
logger.error("ResourceFetchAction empty resources mapping data resourceOpt = " + resourceOpt)
Results.Unauthorized
}
}
case _ => {
logger.error("System does not get x-api-key, bad request.")
Left(Results.Unauthorized)
}
}
}
}
}
#4 Match the Mapping with resources
package com.sillycat.services.auth
import com.sillycat.utils.IncludeLogger
import play.api.mvc.{Results, ActionFilter}
import scala.concurrent.Future
object AuthCampaignCheckAction
extends ActionFilter[ResourceRequest]
with IncludeLogger
{
def filter[A](request: ResourceRequest[A]) = Future.successful {
val campaignID = request.campaignID
val resources = request.campaigns
logger.trace("AuthCampaignCheckAction campaignID = " + campaignID)
logger.trace("AuthCampaignCheckAction resources = " + resources)
if (resources.contains(campaignID)){
logger.trace("AuthCampaignCheckAction, You are authorized!")
None
} else{
logger.warn("AuthCampaignCheckAction, Unauthorized!")
Some(Results.Unauthorized)
}
}
}
After that, when we wants to use them in the Controller.
…snip...
with IncludeAuthService
..snip...
def addJob(
@ApiParam(name="campaignID",value="campaign ID",defaultValue=“xxxxx",required=true,allowMultiple=false)
@PathParam("campaignID")
campaignID:String
) = (TokenFetchAction andThen ResourceFetchAction(campaignID) andThen AuthCampaignCheckAction)(BodyParsers.parse.json) { implicit request =>
…snip...
References:
https://www.playframework.com/documentation/2.4.x/ScalaActionsComposition
http://stackoverflow.com/questions/19868153/authorisation-check-in-controller-scala-play
发表评论
-
Stop Update Here
2020-04-28 09:00 316I will stop update here, and mo ... -
NodeJS12 and Zlib
2020-04-01 07:44 475NodeJS12 and Zlib It works as ... -
Docker Swarm 2020(2)Docker Swarm and Portainer
2020-03-31 23:18 368Docker Swarm 2020(2)Docker Swar ... -
Docker Swarm 2020(1)Simply Install and Use Swarm
2020-03-31 07:58 369Docker Swarm 2020(1)Simply Inst ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 336Traefik 2020(1)Introduction and ... -
Portainer 2020(4)Deploy Nginx and Others
2020-03-20 12:06 431Portainer 2020(4)Deploy Nginx a ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 436Private Registry 2020(1)No auth ... -
Docker Compose 2020(1)Installation and Basic
2020-03-15 08:10 374Docker Compose 2020(1)Installat ... -
VPN Server 2020(2)Docker on CentOS in Ubuntu
2020-03-02 08:04 455VPN Server 2020(2)Docker on Cen ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 385Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 478NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 423Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 337Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 247GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 451GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 328GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 314Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 318Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 294Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 312Serverless with NodeJS and Tenc ...
相关推荐
在Play Framework中,安全模块是一个重要的组件,它帮助开发者实现基本的认证(Authentication)和授权(Authorization)功能,确保应用的安全性。 安全模块Secure module 提供了一个基础的控制器`controllers....
使用 Deadbolt-2 的 Play-Framework 动态授权在这个示例应用程序中,我们使用Deadbolt-2来维护使用Play-Framework 2.3.x 、 H2 数据库和ReactiveMongo-Extensions 的动态授权。 我们正在使用Deadbolt-2通过 dynaimc ...
Explains the role of Controllers in the MVC framework and what role models play in binding and data access strategies Demonstrates how to display and process forms Covers the new features added in ...
这个工具充分利用了 Play Framework 的优势,为开发者提供了一套简洁、高效的解决方案,帮助他们快速集成登录、注册、权限管理等核心认证模块。 在 Play Framework 中,身份验证通常涉及到以下几个关键知识点: 1....
implement efficient data paging, reuse UI using master pages and partials, secure the application using authentication and authorization, use AJAX to deliver dynamic updates and interactive map ...
implement efficient data paging, reuse UI using master pages and partials, secure the application using authentication and authorization, use AJAX to deliver dynamic updates and interactive map ...
implement efficient data paging, reuse UI using master pages and partials, secure the application using authentication and authorization, use AJAX to deliver dynamic updates and interactive map ...
implement efficient data paging, reuse UI using master pages and partials, secure the application using authentication and authorization, use AJAX to deliver dynamic updates and interactive map ...
implement efficient data paging, reuse UI using master pages and partials, secure the application using authentication and authorization, use AJAX to deliver dynamic updates and interactive map ...
Play Framework是一个用Java和Scala构建现代Web应用的开源框架,它强调代码的简洁性和可测试性,提供了一种快速开发高性能Web应用的方式。 **Play Framework 2.3.9** Play Framework 2.3.x系列是该框架的一个稳定...
play-pac4j项目是Play框架v2 Web应用程序和Web服务的简单而强大的安全性库,它支持身份验证和授权,还支持注销和CSRF保护等高级功能。 它可以与Deadbolt一起使用。 它基于Play 2.8(Scala v2.12或v2.13)和v5 。 它...
1. **Java Web开发框架**:Java提供了多个Web开发框架,如Spring MVC、Struts2和Play Framework等,它们可以简化Web应用的开发,提高代码的可维护性和可扩展性。Spring MVC是目前最常用的框架,它提供了一个模型-...
"一个不错的Java Web框架"可能指的是Spring、Struts、Hibernate、Play Framework等众多优秀框架之一,这里我们将以Spring Framework为例,因为它在Java Web开发领域具有广泛的应用和影响力。 Spring Framework是一...
Pac4J 是一个轻量级、可扩展的安全库,适用于多种 web 框架,如 Spring Security 和 Play Framework。JWT(JSON Web Token)则是一种安全地在各方之间传输信息的开放标准,常用于身份验证和授权。 在这个压缩包中,...
2. 用户界面:为了提供用户友好的体验,Rosei可能包含一个基于Web的用户界面,可能使用Java Servlets、JSP(JavaServer Pages)或者现代的Java Web框架如Spring Boot、Play Framework等来构建。 3. 搜索引擎集成:...
7. **安全性**:Java EE提供了安全管理、认证和授权等服务,如JAAS(Java Authentication and Authorization Service)和Spring Security,用于保护服务器资源的安全。 8. **持续集成/持续部署(CI/CD)**:在开发...
4. **Java Web框架**:Spring Boot、Grails、Play Framework等是流行的Java Web框架,它们简化了Web服务器的配置和开发,提供了MVC(模型-视图-控制器)架构模式,便于创建复杂的Web应用。 5. **WebSocket**:Java...
5. **Web框架**:在Java世界里,有许多流行的Web框架,如Spring MVC、Struts和Play Framework,它们简化了Web应用的开发,提供了更高级别的抽象和功能,如依赖注入、模板引擎和安全控制。 6. **RESTful API设计**:...
在实际项目中,开发者可以通过构建Scala OAuth2库的实例,将它集成到现有的Web框架(如Play Framework)或任何需要OAuth2认证的应用中。此外,由于Scala的类型系统和函数式编程特性,这个库往往具有良好的代码可读性...