ラベル ASP.NET Identity の投稿を表示しています。 すべての投稿を表示
ラベル ASP.NET Identity の投稿を表示しています。 すべての投稿を表示

2021年9月17日金曜日

ASP.NET Identity メモ

 認証用DBの作成方法

テーブルを生成する

Code Firstで実行時に生成されるのはデモとしてはいいのですけど、実務では開発者の意図するタイミングで生成しておきたいこともあります。その場合は、Migrationしてやればいいようです。

ツール -> NuGetパッケージマネージャー -> パッケージマネジャーコンソールを開き、

Enable-Migrations
Add-Migration migration_filename
Update-Database

 

2016年1月6日水曜日

ASP.Net Identity Logout

var AutheticationManager = HttpContext.GetOwinContext().Authentication;
AuthenticationManager.SignOut();

2015年11月7日土曜日

ASP.NET MVC Identityによるカスタムログイン

usernamagerを使えば楽なのだが
ユーザー管理は基幹システムで管理するので
Webサービス経由でログイン情報を取得する。

他のサンプルを見ても、usermanager経由だったので、ClaimsIdentityを生成する方法が
分からんので、単純にセッション変数を使ってログインを使用かな~と思ったが
何とかサンプルが有ったので、記述しておく。

AccountControllerを以下のように修正

using Microsoft.AspNet.Identity;  
using Microsoft.Owin.Security;  
using System.Security.Claims;  
using System.Web;  
using System.Web.Mvc;

namespace Mvc5AuthSample.Controllers  
{
    public class AccountController : Controller
    {
      public ActionResult Login()
      {
        return View();
      }

      [HttpPost]
      public ActionResult Login(string username, string password)
      {
        if (username == "alice" && password == "supersecret")
        {
           HttpContext.GetOwinContext().Authentication
             .SignOut(DefaultAuthenticationTypes.ExternalCookie);

           Claim claim1 = new Claim(ClaimTypes.Name, username);
           Claim[] claims = new Claim[] { claim1 };
           ClaimsIdentity claimsIdentity = 
             new ClaimsIdentity(claims,
               DefaultAuthenticationTypes.ApplicationCookie);

           HttpContext.GetOwinContext().Authentication
            .SignIn(new AuthenticationProperties() 
              { IsPersistent = false }, claimsIdentity);

           return Redirect("/Home");
        }
        else
        {
           ModelState.AddModelError("", 
            "Invalid username or password.");
        }

        return View();
      }
    }
}


元ネタ
http://aspnetguru.com/adding-authentication-to-asp-net-mvc-5/



2015年10月29日木曜日

ASP.NET MVC identityで使うテーブル名の変更

Models/IdentityModels.cs の中に以下の記述を追加

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);

            //こんな感じで好きな名前を定義します
            modelBuilder.Entity<IdentityUser>().ToTable("mUsers").Property(p => p.Id).HasColumnName("UserId");
            modelBuilder.Entity<ApplicationUser>().ToTable("mUsers").Property(p => p.Id).HasColumnName("UserId");
            modelBuilder.Entity<IdentityUserRole>().ToTable("dUserRoles");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("dUserLogins");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("dUserClaims");
            modelBuilder.Entity<IdentityRole>().ToTable("mRoles");
}