asp.net6
【Logout.cshtml.cs】
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace WebApplication2.Areas.Identity.Pages.Account
{
[AllowAnonymous] public class LogoutModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly ILogger<LogoutModel> _logger;
public LogoutModel(SignInManager<IdentityUser> signInManager, ILogger<LogoutModel> logger) { _signInManager = signInManager; _logger = logger; }
public void OnGet() { }
public async Task<IActionResult> OnPost(string returnUrl = null) {
await _signInManager.SignOutAsync(); _logger.LogInformation("User logged out.");
// // 外部Cookieをクリアする // await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
//await HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
//await HttpContext.SignOutAsync();
//await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
//HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);
if (returnUrl != null) { return LocalRedirect(returnUrl); } else { //return RedirectToPage(); return LocalRedirect("/Identity/Account/Logout");
//return RedirectToPage("/Account/SignedOut"); } } }
}
【Logout.cshtml】
@page
@model LogoutModel
@{ ViewData["Title"] = "ログアウト画面"; }
<header>
<h1>@ViewData["Title"]</h1> <p>正常にログアウトしました。</p> <p>@User.Identity.Name</p> <p>@User.Identity.IsAuthenticated</p>
</header>
【Register.cshtml.cs】
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace WebApplication2.Areas.Identity.Pages.Account
{
[AllowAnonymous] public class RegisterModel : PageModel { private readonly SignInManager<IdentityUser> _signInManager; private readonly UserManager<IdentityUser> _userManager; private readonly ILogger<RegisterModel> _logger; private readonly IEmailSender _emailSender;
public RegisterModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, ILogger<RegisterModel> logger, IEmailSender emailSender) { _userManager = userManager; _signInManager = signInManager; _logger = logger; _emailSender = emailSender; }
[BindProperty] public InputModel Input { get; set; }
public string ReturnUrl { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public class InputModel { [Required] [EmailAddress(ErrorMessage = "メールアドレスを入力してください。")] [Display(Name = "メールアドレス")] public string Email { get; set; }
//[Required] [StringLength(100, ErrorMessage = "{0} は {2} 文字から {1} 文字の間で設定してください。", MinimumLength = 0)] [DataType(DataType.Password)] [Display(Name = "パスワード")] public string Password { get; set; }
[DataType(DataType.Password)] [Display(Name = "確認パスワード")] [Compare("Password", ErrorMessage = "パスワードと確認パスワードが一致しません。")] public string ConfirmPassword { get; set; } }
public async Task OnGetAsync(string returnUrl = null) { ReturnUrl = returnUrl; ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); }
public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()) .ToList(); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; //var result = await _userManager.CreateAsync(user, Input.Password); var result = await _userManager.CreateAsync(user, "a"); if (result.Succeeded) { _logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code }, protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("RegisterConfirmation", new { email = Input.Email }); } else { await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } }
// If we got this far, something failed, redisplay form return Page(); } }
}
【Register.cshtml】
@page
@model RegisterModel
@{ ViewData["Title"] = "Register"; }
<h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-4"> <form asp-route-returnUrl="@Model.ReturnUrl" method="post"> <h4>Create a new account.</h4> <hr /> <div asp-validation-summary="All" class="text-danger"></div> <div class="form-group"> <label asp-for="Input.Email"></label> <input asp-for="Input.Email" class="form-control" /> <span asp-validation-for="Input.Email" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Input.Password"></label> <input asp-for="Input.Password" class="form-control" /> <span asp-validation-for="Input.Password" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Input.ConfirmPassword"></label> <input asp-for="Input.ConfirmPassword" class="form-control" /> <span asp-validation-for="Input.ConfirmPassword" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Register</button> </form> </div> <div class="col-md-6 col-md-offset-2"> <section> <h4>Use another service to register.</h4> <hr /> @{ if ((Model.ExternalLogins?.Count ?? 0) == 0) { <div> <p> There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a> for details on setting up this ASP.NET application to support logging in via external services. </p> </div> } else { <form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal"> <div> <p> @foreach (var provider in Model.ExternalLogins) { <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>} </p> </div> </form> } } </section> </div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
- 最終更新:2021-01-31 20:05:52