Nancy's Forms の簡単な使い方 authentication_html/css_WEB-ITnose
1. はじめに
Microsoft が発表した ASP.NET Identity テクノロジについては、誰もが聞いたことがあると思います。
偶然にも、Nancy にも Authentication と呼ばれる同様のテクノロジがあります。どちらも同様のセキュリティ テクノロジをいくつか使用しています
(ASP.NET Identity の内部実装は見ていません。その簡単な使用法から判断します)
正式な紹介を始める前に、ASP.NET Identity に関する優れた記事をいくつかお勧めします
r01cn の ASP.NET Identity シリーズ チュートリアル (目次)
Jesse の MVC5 - ASP .NET Identity ログインの原則 - クレームベース認証と OWIN
それでは、デモを使用してフォーム認証を簡単に使用する方法を紹介しましょう
2. 簡単な使用方法
1) 、空の asp.net プロジェクトを作成します
2)、NuGet を通じて対応するパッケージをインストールします
1 Install-Package Nancy2 Install-Package Nancy.Hosting.Aspnet3 Install-Package Nancy.Authentication.Forms4 Install-Package Dapper
データベース アクセスに関しては、Dapper もインストールしました
3)、データテーブル
1 CREATE TABLE [dbo].[SystemUser]( 2 [SystemUserId] [uniqueidentifier] NOT NULL, 3 [SystemUserName] [nvarchar](50) NOT NULL, 4 [SystemUserPassword] [nvarchar](50) NOT NULL, 5 CONSTRAINT [PK_SystemUser] PRIMARY KEY CLUSTERED 6 ( 7 [SystemUserId] ASC 8 )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] 9 ) ON [PRIMARY]10 GO
を作成し、同時に 2 つのデータをテーブルに挿入しました
1 INSERT INTO [dbo].[SystemUser]([SystemUserId],[SystemUserName],[SystemUserPassword])2 VALUES(newid(),'catcher','123')3 INSERT INTO [dbo].[SystemUser]([SystemUserId],[SystemUserName],[SystemUserPassword])4 VALUES(newid(),'admin','123')
注: これはデモですので、パスワードは暗号化されません
4)、対応するフォルダーを作成します
Models はモデルを保存するために使用されます
Modules は対応する操作を保存するために使用されます
ビューはビューの保存に使用されます
5)、モデル SystemUser.cs を書き込みます
1 public class SystemUser2 {3 public Guid SystemUserId { get; set; }4 public string SystemUserName { get; set; }5 public string SystemUserPassword { get; set; }6 }
6)、HomeModule.cs を書き込みます
1 using Dapper; 2 using Nancy; 3 using Nancy.Authentication.Forms; 4 using Nancy.ModelBinding; 5 using NancyDemoForFormsauthentication.Models; 6 using System.Data; 7 using System.Data.SqlClient; 8 using System.Linq; 9 namespace NancyDemoForFormsauthentication.Modules10 {11 public class HomeModule : NancyModule12 {13 public HomeModule()14 {15 Get["/"] = _ =>16 {17 return View["index"];18 };19 Get["/login"] = _ =>20 {21 return View["login"];22 };23 Post["/login"] = _ =>24 {25 var loginUser = this.Bind<SystemUser>();26 SystemUser user = GetValidUser(loginUser.SystemUserName, loginUser.SystemUserPassword);27 if (user == null)28 {29 return Response.AsText("出错了", "text/html;charset=UTF-8");30 }31 return this.LoginAndRedirect(user.SystemUserId, fallbackRedirectUrl: "/secure");32 };33 }34 private readonly string sqlconnection =35 "Data Source=127.0.0.1;Initial Catalog=NancyDemo;User Id=sa;Password=dream_time1314;";36 private SqlConnection OpenConnection()37 {38 SqlConnection connection = new SqlConnection(sqlconnection);39 connection.Open();40 return connection;41 }42 private SystemUser GetValidUser(string name, string pwd)43 {44 using (IDbConnection conn = OpenConnection())45 {46 const string query = "select * from SystemUser where SystemUserName=@SystemUserName and SystemUserPassword=@SystemUserPassword";47 return conn.Query<SystemUser>(query, new { SystemUserName = name, SystemUserPassword = pwd }).SingleOrDefault();48 }49 }50 }51 }
このうち、ログインポストメソッド
では静的メソッド LoginAndRedirect が使用されています。 このメソッドは ModuleExtensions.cs にあり、戻り値の型は Response
1 public static Response LoginAndRedirect(this INancyModule module, Guid userIdentifier, DateTime? cookieExpiry = null, string fallbackRedirectUrl = "/")2 {3 return FormsAuthentication.UserLoggedInRedirectResponse(module.Context, userIdentifier, cookieExpiry, fallbackRedirectUrl);4 }
であることがわかります。メソッド名 これが何のためにあるのかを理解してください。
中国語の文字化けを防ぐため、Response.AsText の後に 2 番目のパラメータもあります。 !
7)、対応するビューを書き込みます
index.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta charset="utf-8" /> 6 </head> 7 <body> 8 <h2>Nancy之基于Forms authentication的简单使用</h2> 9 <p>访问需要权限的页面</p>10 <a href="/secure">secure</a>11 </body>12 </html>
login.html
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title></title> 5 <meta charset="utf-8" /> 6 </head> 7 <body> 8 <form method="post" action="/login"> 9 <label>姓名:</label><input type="text" name="SystemUserName" /><br />10 <label>密码:</label><input type="password" name="SystemUserPassword" /><br />11 <input type="submit" />12 </form>13 </body>14 </html>
8)、SecureModule.cs を書き込みます
1 using Nancy; 2 using Nancy.Security; 3 4 namespace NancyDemoForFormsauthentication.Modules 5 { 6 public class SecureModule : NancyModule 7 { 8 public SecureModule() 9 {10 this.RequiresAuthentication();11 Get["/secure"] = _ =>12 {13 return "Hello ," + this.Context.CurrentUser.UserName;14 };15 }16 }17 }
その中で
1 this.RequiresAuthentication();
この文が鍵です! !合格するには検証が必要であることを示します。 Nancy.Security 名前空間
にあり、認証されたアクセス後に現在のユーザー名が出力されます。
9)、Bootstraper.cs を作成します
1 using Nancy; 2 using Nancy.Authentication.Forms; 3 using Nancy.TinyIoc; 4 using Nancy.Bootstrapper; 5 namespace NancyDemoForFormsauthentication 6 { 7 public class Bootstrapper : DefaultNancyBootstrapper 8 { 9 protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)10 {11 base.ConfigureRequestContainer(container, context);12 container.Register<IUserMapper, UserMapper>();13 }14 protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)15 {16 base.RequestStartup(container, pipelines, context);17 var formsAuthConfiguration = new FormsAuthenticationConfiguration18 {19 RedirectUrl = "~/login",20 UserMapper = container.Resolve<IUserMapper>(),21 };22 FormsAuthentication.Enable(pipelines, formsAuthConfiguration);23 }24 }25 }
これは重要なステップです。 ! !
RequestStartup で FormsAuthentication を有効にするには! !
同時に、UserMapper を登録するために FormsAuthenticationConfiguration
を構成する必要があるため、次のステップは UserMapper
10) を実装し、UserMapper.cs<🎜 を記述することです。 >
1 using Dapper; 2 using Nancy; 3 using Nancy.Authentication.Forms; 4 using Nancy.Security; 5 using NancyDemoForFormsauthentication.Models; 6 using System; 7 using System.Data; 8 using System.Data.SqlClient; 9 using System.Linq;10 namespace NancyDemoForFormsauthentication11 {12 public class UserMapper : IUserMapper13 {14 public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)15 {16 using (IDbConnection conn = OpenConnection())17 {18 const string query = "select * from SystemUser where SystemUserId=@SystemUserId";19 var user = conn.Query<SystemUser>(query, new { SystemUserId = identifier }).SingleOrDefault();20 if (user == null)21 {22 return null;23 }24 else25 {26 return new UserIdentity27 {28 UserName = user.SystemUserName,29 Claims = new[] { "SystemUser"}30 };31 }32 }33 }34 private readonly string sqlconnection =35 "Data Source=127.0.0.1;Initial Catalog=NancyDemo;User Id=sa;Password=dream_time1314;";36 private SqlConnection OpenConnection()37 {38 SqlConnection connection = new SqlConnection(sqlconnection);39 connection.Open();40 return connection;41 }42 }43 }
11)、UserIdentity.cs を書き込みます
1 using Nancy.Security; 2 using System.Collections.Generic; 3 namespace NancyDemoForFormsauthentication 4 { 5 public class UserIdentity : IUserIdentity 6 { 7 public string UserName { get; set; } 8 public IEnumerable<string> Claims { get; set; } 9 }10 }
安全なリンクにアクセスすると、自動的にログイン インターフェイスにジャンプすることがわかりました。 !
ユーザー名とパスワードを入力します
ログインに成功し、安全なページに戻ります。
間違ったユーザー名とパスワードを入力した場合
最後に、これがサンプルコードです:
https : //github.com/hwqdt/Demos/tree/master/src/NancyDemoForFormsauthentication

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











HTMLは、簡単に学習しやすく、結果をすばやく見ることができるため、初心者に適しています。 1)HTMLの学習曲線はスムーズで簡単に開始できます。 2)基本タグをマスターして、Webページの作成を開始します。 3)柔軟性が高く、CSSおよびJavaScriptと組み合わせて使用できます。 4)豊富な学習リソースと最新のツールは、学習プロセスをサポートしています。

HTMLはWeb構造を定義し、CSSはスタイルとレイアウトを担当し、JavaScriptは動的な相互作用を提供します。 3人はWeb開発で職務を遂行し、共同でカラフルなWebサイトを構築します。

webdevelopmentReliesOnhtml、css、andjavascript:1)htmlStructuresContent、2)cssStylesit、および3)Javascriptaddsinteractivity、形成、

GiteEpages静的Webサイトの展開が失敗しました:404エラーのトラブルシューティングと解像度Giteeを使用する

Anexampleapalofastartingtaginhtmlis、それはaperginsaparagraph.startingtagsaresentionentientiontheyinitiateelements、definetheirtypes、およびarecrucialforurturingwebpagesandcontingthomedomを構築します。

画像をクリックした後、散乱と周囲の画像を拡大する効果を実現するには、多くのWebデザインがインタラクティブな効果を実現する必要があります。特定の画像をクリックして周囲を作成してください...

HTML、CSS、およびJavaScriptは、Web開発の3つの柱です。 1。HTMLは、Webページ構造を定義し、などなどのタグを使用します。2。CSSは、色、フォントサイズなどのセレクターと属性を使用してWebページスタイルを制御します。

Y軸位置Webアノテーション機能の適応アルゴリズムこの記事では、単語文書と同様の注釈関数、特に注釈間の間隔を扱う方法を実装する方法を探ります...
