1. 程式人生 > >使用ClaimsIdentity來實現登錄授權

使用ClaimsIdentity來實現登錄授權

isp pub uri img eid esp sem soft web項目

背景:以前做登錄時用的都是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>

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

使用ClaimsIdentity來實現登錄授權