ASP.NETユーザ管理(ASP.NET Identityフレームワーク)の9回目です。前回は、2要素認証を使ってみました。今回はパスワードリセットです。パスワードリセットですが、要するにパスワードを忘れた場合の処理です。デフォルトでWebFormのテンプレートに組み込まれているので、その処理を有効にするという変更です。(ホーム)\Account\Forgot.aspxです。
今回のソース一式はこちらです。今回の部分は(ISY07)ではじまるコメントを付けています。メール送信処理についてはアカウントを設定するか、メール送信処理を削除するか等で動作させてください。
まず、Forgot.aspxに以下のメッセージを追加して初期状態では非表示にしました。以下追加部分だけです。
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Label ID="lblConfirm" runat="server" Text="メールを確認してパスワードを再設定してください。" Visible="False"></asp:Label>
</div>
</div>
ビハインドコードが以下です。
using System;
using System.Web;
using System.Web.UI;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using ASPNETWebFormsIdentity.Models;
namespace ASPNETWebFormsIdentity.Account
{
public partial class ForgotPassword : Page
{
protected void Page_Load(object sender, EventArgs e)
{
//(ISY07)追加
if (!IsPostBack) {
lblConfirm.Visible = false;
}
}
protected void Forgot(object sender, EventArgs e)
{
if (IsValid)
{
// Validate the user password
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
ApplicationUser user = manager.FindByName(Email.Text);
if (user == null || !manager.IsEmailConfirmed(user.Id))
{
FailureText.Text = "The user either does not exist or is not confirmed.";
ErrorMessage.Visible = true;
return;
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send email with the code and the redirect to reset password page
string code = manager.GeneratePasswordResetToken(user.Id);
string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code);
//(ISY07)URL作成
string domainName = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
string url = domainName + callbackUrl;
//(ISY07)HTMLテキストの作成
string linktext = "このリンクをクリックすることによってパスワードをリセットしてください。 " + url;
//manager.SendEmail(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>.");
manager.SendEmail(user.Id, "パスワードのリセット", linktext);
lblConfirm.Visible = true;
}
}
}
}
処理としては、ユーザ登録の時と同様にリンクのテキストをメールで送信しています。メール送信の処理は、ASP.NETユーザ管理(その3)ユーザ登録時のメール確認でのメール送信と同じ実装が使われます。
これでこのシリーズは終了です。今回のシリーズの一連の処理は管理的な処理で実際にはこの管理の元に何かしらのサービスや、業務処理を構築して運用していくことになります。実際には、その何かしらの「サービス」や「業務処理」が一番大事な部分ですが、やはり、ユーザ管理、ロール管理は必要になってくるので取り上げました。