LoginSignup
0
0

More than 5 years have passed since last update.

Nancy+OWINでセキュアなページを作成する

Posted at

一式を https://github.com/ken200/OwinAuthWithNancy に配置しています。

本件に関連するソースコードは MyNancyModule.cs に記載しています。

必要パッケージ(Nancy関係のみ)

  • Nancy
  • Nancy.MSOwinSecurity
  • Nancy.Owin

Nancyの認証はASP.NET、OWINとは切り離されているため、Nancy.MSOwinSecurityパッケージをインストールしてOWINのセキュリティー機構を利用できるようにする必要があります。

ソースコード

SecureModuleクラスのほうです。

/secureの定義で呼び出している this.RequiresMSOwinAuthentication() で非認証時アクセス不可(Exception吐く)設定しています。

this.Context.GetMSOwinUser() で認証ユーザー情報を取得できます。

public class MyNancyModule : NancyModule
{
    public MyNancyModule() : base()
    {
        Get["/"] = _ => 
        {
            return "hello";
        };

        Get["/hoge"] = _ =>
        {
            return "hoge";
        };

        Get["/login"] = _ =>
        {
            return new Nancy.Responses.HtmlResponse()
            {
                Contents = (s) => 
                {
                    using (var sw = new StreamWriter(s, System.Text.Encoding.UTF8)) 
                    {
                        sw.Write(@"
<html>
<head>
<title>ログイン</title>
</head>
<body>
<form action=""/login?RedirectUrl=/secure"" method=""post"">
<label for=""username"">ユーザー名</label>
<input type=""text"" name=""username"" />
<input type=""submit"" />
</form>
</html>
");
                    }
                }
            };
        };
    }
}

public class SecureModule : NancyModule
{
    public SecureModule()
    {
        Get["/secure"] = _ =>
        {
            this.RequiresMSOwinAuthentication();
            var user = this.Context.GetMSOwinUser();
            return string.Format("hello, {0}. this page is secure!!", user.Identity.Name);
        };
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0