Nancy 學習-身份認證(Forms authentication) 繼續跨平台


開源 示例代碼:https://github.com/linezero/NancyDemo 

上篇講解Nancy的Basic Authentication,現在來學習Nancy 的Forms身份認證。

本篇主要講解Forms authentication ,Forms身份認證

 

說明:本篇示例是基於 Nancy 1.4.3。Nancy 2.0預覽版 已經發布,版本改動較大,故特此說明。

 

准備

安裝 Nancy.Authentication.Forms

Install-Package Nancy.Authentication.Forms -Version 1.4.1

實戰

繼續在示例中添加代碼,沒有新建項目。

1.實現 IUserMapper 接口

新建一個 FormsUserMapper 類實現接口 IUserMapper

    public class FormsUserMapper : IUserMapper
    {
        private static List<Tuple<string, string, Guid>> users = new List<Tuple<string, string, Guid>>();

        public FormsUserMapper()
        {
            users.Add(new Tuple<string, string, Guid>("linezero", "demo", new Guid("19FF111D-DCF5-4FFC-9CFA-4C256E7C9748")));
            users.Add(new Tuple<string, string, Guid>("nancy", "demo", new Guid("18FF111D-DCF5-4FFC-9CFA-4C256E7C9748")));
        }

        public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
        {
            var userRecord = users.Where(u => u.Item3 == identifier).FirstOrDefault();

            return userRecord == null
                       ? null
                       : new FormsUser { UserName = userRecord.Item1 };
        }

        public static Guid? ValidateUser(string username, string password)
        {
            var userRecord = users.Where(u => u.Item1 == username && u.Item2 == password).FirstOrDefault();

            if (userRecord == null)
            {
                return null;
            }

            return userRecord.Item3;
        }
    }

這里我簡單的寫了個多個用戶,而不是之前的單個用戶。

Nancy身份認證都涉及到IUserIdentity 接口,這里我為了區分之前的Basic 認證,新建了一個FormsUser 類實現IUserIdentity。

2.添加登錄登出

添加一個module ,來實現登錄登出。

新建FormsModule 類,並建立對應文件夾。

新建一個登錄頁:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>登錄</title>
</head>
<body>
    <form method="post">
        Username
        <input type="text" name="Username" />
        <br />
        Password
        <input name="Password" type="password" />
        <br />
        Remember Me
        <input name="RememberMe" type="checkbox" value="True" />
        <br />
        <input type="submit" value="Login" />
    </form>
    @if (Model.Errored)
    {
        <div id="errorBox" class="floatingError">用戶名或密碼錯誤</div>
    }
</body>
</html>

 

接受登錄信息:

            Post["/login"] = r =>
            {
                var userGuid = FormsUserMapper.ValidateUser((string)this.Request.Form.Username, (string)this.Request.Form.Password);

                if (userGuid == null)
                {
                    return this.Context.GetRedirect("~/forms/login?error=true&username=" + (string)this.Request.Form.Username);
                }

                DateTime? expiry = null;
                if (this.Request.Form.RememberMe.HasValue)
                {
                    expiry = DateTime.Now.AddDays(7);
                }

                return this.Login(userGuid.Value, expiry);
            };

更多詳細代碼,請看示例代碼。

3.配置啟用Forms身份認證

在Bootstrapper 的ApplicationStartup 添加如下代碼:

            container.Register<IUserMapper, FormsUserMapper>();//Forms 認證
            var formsAuthConfiguration = new FormsAuthenticationConfiguration()
            {
                RedirectUrl = "~/forms/login",
                UserMapper = container.Resolve<IUserMapper>(),
            };
            FormsAuthentication.Enable(pipelines, formsAuthConfiguration);//啟用Forms 認證

在需要授權的Module 加上就可以開啟。

            this.RequiresAuthentication();

由於示例代碼存在Basic 認證,我將其注釋了。只保留Forms。

4.實現效果

訪問: http://localhost:9000/

 

成功登錄后 訪問:http://localhost:9000/forms/

 

 示例代碼下載:https://github.com/linezero/NancyDemo

 示例代碼包含之前示例,並且會持續更新,歡迎大家Star。

如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM