使用ClaimsIdentity來實現登錄授權


背景:以前做登錄時用的都是FormsAuthentication.SetAuthCookie(model.UID, IsRemeber),但是有一個不好,不能存儲多個值,有時候我們既想存儲登錄用戶的UID又想存儲用戶名,以前都是將兩者拼接成字符串,用的時候在split出來,比較麻煩,現在用ClaimsIdentity就很方便。

1、登錄時驗證通過存儲

  ClaimsIdentity ci = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
                    ci.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, model.UserName));
                    ci.AddClaim(new Claim(ClaimTypes.NameIdentifier, model.UID));
                    ci.AddClaim(new Claim("HspUID", model.HspUID));
                    AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = IsRemeber }, ci);

需要用到下面的

 private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

2、獲取值

//獲取UID
User.Identity.GetUserId();
//獲取Name
User.Identity.Name;
//獲取HspUID
var claimIdentity = (ClaimsIdentity)User.Identity;
var HspUID = claimIdentity.FindFirstValue("HspUID");

3、App_Start里創建Startup.Auth.cs

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Yuwell.PressureManage.Web
{
    public partial class Startup
    {
        public void ConfigureAuth(IAppBuilder app)
        {


            // 使應用程序可以使用 Cookie 來存儲已登錄用戶的信息
            // 並使用 Cookie 來臨時存儲有關使用第三方登錄提供程序登錄的用戶的信息
            // 配置登錄 Cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),              
            });
       
        }
    }
}

4、Web項目里添加Startup類

using Hangfire;
using Hangfire.MemoryStorage;
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

[assembly: OwinStartupAttribute(typeof(Test.Web.Startup))]
namespace Yuwell.PressureManage.Web
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            GlobalConfiguration.Configuration.UseMemoryStorage();
            app.UseHangfireServer();
            app.UseHangfireDashboard();
        }
    }
}

 

需要用到的包

 記得Web.config里configSections節點下加下面的配置

  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>

好了,好像就這么多了,結束!!!!!!


免責聲明!

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



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