Add HTTPBasicAuth middleware
This commit is contained in:
parent
8b6700695d
commit
743fd3682d
4 changed files with 65 additions and 0 deletions
25
spec/middleware/http_basic_auth_spec.cr
Normal file
25
spec/middleware/http_basic_auth_spec.cr
Normal file
|
@ -0,0 +1,25 @@
|
|||
require "../spec_helper"
|
||||
|
||||
describe "Kemal::Middleware::HTTPBasicAuth" do
|
||||
it "goes to next handler with correct credentials" do
|
||||
auth_handler = Kemal::Middleware::HTTPBasicAuth.new("serdar", "123")
|
||||
request = HTTP::Request.new(
|
||||
"GET",
|
||||
"/",
|
||||
headers: HTTP::Headers{"Authorization": "Basic c2VyZGFyOjEyMw=="},
|
||||
)
|
||||
response = auth_handler.call(request)
|
||||
response.status_code.should eq 404
|
||||
end
|
||||
|
||||
it "returns 401 with incorrect credentials" do
|
||||
auth_handler = Kemal::Middleware::HTTPBasicAuth.new("serdar", "123")
|
||||
request = HTTP::Request.new(
|
||||
"GET",
|
||||
"/",
|
||||
headers: HTTP::Headers{"Authorization": "NotBasic"},
|
||||
)
|
||||
response = auth_handler.call(request)
|
||||
response.status_code.should eq 401
|
||||
end
|
||||
end
|
|
@ -1,5 +1,6 @@
|
|||
require "spec"
|
||||
require "../src/kemal/*"
|
||||
require "../src/kemal/middleware/*"
|
||||
|
||||
include Kemal
|
||||
|
||||
|
|
|
@ -20,3 +20,9 @@ macro redirect(url)
|
|||
env.response.headers.add "Location", {{url}}
|
||||
env.response.status_code = 301
|
||||
end
|
||||
|
||||
# Uses Kemal::Middleware::HTTPBasicAuth to easily add HTTP Basic Auth support.
|
||||
macro basic_auth(username, password)
|
||||
auth_handler = Kemal::Middleware::HTTPBasicAuth.new("serdar", "123")
|
||||
Kemal.config.add_handler auth_handler
|
||||
end
|
||||
|
|
33
src/kemal/middleware/http_basic_auth.cr
Normal file
33
src/kemal/middleware/http_basic_auth.cr
Normal file
|
@ -0,0 +1,33 @@
|
|||
require "base64"
|
||||
|
||||
module Kemal::Middleware
|
||||
# This middleware adds HTTP Basic Auth support to your application.
|
||||
# Returns 401 "Unauthorized" with wrong credentials.
|
||||
#
|
||||
# auth_handler = Kemal::Middleware::HTTPBasicAuth.new("username", "password")
|
||||
# Kemal.config.add_handler auth_handler
|
||||
#
|
||||
class HTTPBasicAuth < HTTP::Handler
|
||||
BASIC = "Basic"
|
||||
AUTH = "Authorization"
|
||||
|
||||
def initialize(@username, @password)
|
||||
end
|
||||
|
||||
def call(request)
|
||||
if request.headers[AUTH]?
|
||||
if value = request.headers[AUTH]
|
||||
if value.size > 0 && value.starts_with?(BASIC)
|
||||
return call_next(request) if authorized?(value)
|
||||
end
|
||||
end
|
||||
end
|
||||
HTTP::Response.new(401, "Unauthorized")
|
||||
end
|
||||
|
||||
def authorized?(value)
|
||||
username, password = Base64.decode_string(value[BASIC.size + 1..-1]).split(":")
|
||||
@username == username && @password == password
|
||||
end
|
||||
end
|
||||
end
|
Loading…
Reference in a new issue