utsushiiro / warden-auth

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

warden-auth

Rackの勉強も兼ねたWarden(General Rack Authentication Framework)をつかった認証基盤作成の簡単なサンプル.

起動

 $ rackup
[2018-09-13 22:20:53] INFO  WEBrick 1.4.2
[2018-09-13 22:20:53] INFO  ruby 2.5.0 (2017-12-25) [x86_64-darwin17]
[2018-09-13 22:20:53] INFO  WEBrick::HTTPServer#start: pid=3550 port=9292
...

動作確認

# トップページにアクセス
$ curl -i --request GET http://localhost:9292/
HTTP/1.1 200 OK
Content-Type: text/html
Transfer-Encoding: chunked
Server: WEBrick/1.4.2 (Ruby/2.5.0/2017-12-25)
Date: Thu, 13 Sep 2018 13:33:58 GMT
Connection: Keep-Alive

Hello Rack!

# ログインしていない状態で保護されたページ(/protected)にアクセス
$ curl -i --request GET http://localhost:9292/protected
HTTP/1.1 401 Unauthorized
Content-Type: text/html
Transfer-Encoding: chunked
Server: WEBrick/1.4.2 (Ruby/2.5.0/2017-12-25)
Date: Thu, 13 Sep 2018 13:34:03 GMT
Connection: Keep-Alive

Unauthorized

# ログインする
$ curl -i --request POST http://localhost:9292/login \
>         --data 'id=sample_user&password=password' \
>         --cookie-jar cookie.txt
HTTP/1.1 200 OK
Content-Type: text/html
Transfer-Encoding: chunked
Server: WEBrick/1.4.2 (Ruby/2.5.0/2017-12-25)
Date: Thu, 13 Sep 2018 13:39:46 GMT
Connection: Keep-Alive
Set-Cookie: rack.session=BAh7B0...省略...4f49f5; path=/; HttpOnly

Hello sample_user!

# 上記コマンドで保存したcookieの中身
$ cat cookie.txt
# Netscape HTTP Cookie File
# https://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_localhost	FALSE	/	FALSE	0	rack.session	BAh7B0...省略...4f49f5

# 保存したcookieをつけて保護されたページ(/protected)にアクセス
$ curl -i --request GET http://localhost:9292/protected \
>         --cookie cookie.txt
HTTP/1.1 200 OK
Content-Type: text/html
Transfer-Encoding: chunked
Server: WEBrick/1.4.2 (Ruby/2.5.0/2017-12-25)
Date: Thu, 13 Sep 2018 13:40:26 GMT
Connection: Keep-Alive

This is a protected page!

Cookieの中身確認

[1] pry(main)> require "base64"
=> true
[2] pry(main)> session_in_cookie = 'BAh7B0...省略...4f49f5'
=> ..略..
[3] pry(main)> session_base64, digest = URI.decode(session_in_cookie).split("--")
=> ..略..
[4] pry(main)> Marshal.load(Base64.decode64(session_base64))
=> {"session_id"=>"fcc414445f3981342c5cb4ee278d067498126ce9558f6831d5bd406196d7722b", "warden.user.default.key"=>"sample_user"}

RackがCookie末尾にdigestを付与しているのでCookie改竄によるなりすまし等は防げるが, Cookieのreplay attackは普通にできちゃう.

参考

About


Languages

Language:Ruby 100.0%