Skip to content

Instantly share code, notes, and snippets.

@cy6erGn0m
Last active October 23, 2018 08:30
Show Gist options
  • Save cy6erGn0m/5252af26da1920dcb61b0da37d4634c5 to your computer and use it in GitHub Desktop.
Save cy6erGn0m/5252af26da1920dcb61b0da37d4634c5 to your computer and use it in GitHub Desktop.
Assigning call attributes based or route with default
private val XFrameOptionsAttribute = AttributeKey<XFrameOptions>("X-Frame-Options")
sealed class XFrameOptions {
object Deny : XFrameOptions() {
override fun toString() = "deny"
}
object SameOrigin : XFrameOptions() {
override fun toString() = "sameorigin"
}
class AllowFrom(val url: String) : XFrameOptions() {
override fun toString(): String = "allow-from $url"
}
}
fun ApplicationCallPipeline.applyFrameOptions(options: XFrameOptions) {
intercept(ApplicationCallPipeline.Features) {
call.attributes.put(XFrameOptionsAttribute, options)
}
}
// create a custom pipeline phase after features but before call
val XFrameOptionsPhase = PipelinePhase("XFrameOptions")
application.insertPhaseAfter(ApplicationCallPipeline.Features, XFrameOptionsPhase)
intercept(XFrameOptionsPhase) {
// intercept every call and check for call's attribute or use "deny" if unspecified
val options = call.attributes.getOrNull(XFrameOptionsAttribute) ?: XFrameOptions.Deny
call.response.header("X-Frame-Options", options.toString())
}
routing {
route("api") {
applyFrameOptions(XFrameOptions.SameOrigin) // assign attribute for the whole route
get("fun1") { ... }
get("fun2") { ... }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment