Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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