Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active February 14, 2019 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ichiroku11/a74e9387f2b6cde2cece5d1141b534f6 to your computer and use it in GitHub Desktop.
Save ichiroku11/a74e9387f2b6cde2cece5d1141b534f6 to your computer and use it in GitHub Desktop.
ASP.NET Core MVC - クッキー認証(https://github.com/ichiroku11/Sample へ)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace WebApp.Controllers {
// アカウントコントローラ
public class AccountController : Controller {
// ログインビュー
[AllowAnonymous]
public IActionResult Login() {
return View();
}
// ログインのポスト処理
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login(IFormCollection fromValues) {
// サインインに必要なプリンシパルを作る
// 本当ならユーザIDとパスワードからユーザを特定して・・・という処理が入るはず
var claims = new[] {
// 適当なユーザ名を登録しておく
new Claim(ClaimTypes.Name, "user01@example.jp"),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
// サインイン
// 認証クッキーをレスポンスに追加
await HttpContext.SignInAsync(principal);
// ログインが必要なアクションにリダイレクト
return RedirectToAction("Index", "Home");
}
// ログアウト
[AllowAnonymous]
public async Task<IActionResult> Logout() {
// サインアウト
// 認証クッキーをレスポンスから削除
await HttpContext.SignOutAsync();
// ログインビューにリダイレクト
return RedirectToAction("Login");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace WebApp.Controllers {
// ログインが必要なコントローラ
public class HomeController : Controller {
public IActionResult Index() {
// ユーザ名を表示する
// User.Identity.Nameは"user01@example.jp"
return Content(User.Identity.Name);
}
}
}
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
</head>
<body>
<form asp-action="Login" method="post">
@* ログインIDやパスワードは省略 *@
<button type="submit">ログイン</button>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace WebApp {
public class Startup {
public void ConfigureServices(IServiceCollection services) {
// クッキー認証に必要なサービスを登録
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => {
// クッキーの名前を変える
options.Cookie.Name = "auth";
// リダイレクトするログインURLも小文字に変える
// ~/Account/Login => ~/account/login
options.LoginPath = CookieAuthenticationDefaults.LoginPath.ToString().ToLower();
});
// MVCで利用するサービスを登録
services.AddMvc(options => {
// グローバルフィルタに承認フィルタを追加
// すべてのコントローラでログインが必要にしておく
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.Configure<RouteOptions>(options => {
// URLは小文字にする
options.LowercaseUrls = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
// パイプラインに認証のミドルウェアを追加する
// HttpContext.Userをセットしてくれる
app.UseAuthentication();
// パイプラインにMVCのミドルウェアを追加する
app.UseMvcWithDefaultRoute();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment