どーも、うぇぶまとりっくすたんと呼ばれる bot ですけど何か?

という訳で WebSecurity クラスです。

概要

ASP.NET メンバーシップの上位レイヤを構成し、アプリケーションに認証および、ユーザー管理機能を提供します。

WebSecurityクラスはすべて静的メンバで構成される静的クラスです。

静的メソッド

bool ChangePassword( string userName, string currentPassword,
string newPassword

指定ユーザーのパスワードを変更します。

パスワードの変更に成功した場合には true 、それ以外の場合には false が返ります。

false 時は以下の可能性があります。

  1. userName で指定されたユーザーが存在しない (UserExists(userName)がnullを返します)
  2. ユーザーの現在パスワードに誤りがある

ユーザーがパスワードを完全に忘れている場合にはこのメソッドでのパスワード変更は機能しません。この場合、以下のシーケンスでユーザーをパスワード変更させます。

  1. GeneratePasswordResetToken( userName ) によりパスワード変更トークンを取得します。
  2. ユーザー登録時に同時に設定させた電子メールアドレス等、Webとは異なる手段によってパスワード変更トークンをユーザーに伝えます。
  3. パスワード変更トークンと新規パスワードをユーザーに入力させ、ResetPassword(  passwordResetToken, newPassword ) によりユーザーのパスワードを更新します。

bool ConfirmAccount( string accountConfirmationToken )

ユーザーのカウントを確認します。

ユーザー登録後の電子メールでの確認結果を反映します。

ユーザーアカウントの作成時に requireConfirmationToken:true で登録させた場合、ユーザーは認証トークンを使って有効化される必要があり、この有効化を行います。

string CreateAccount( string userName, string passward,
bool requireConfirmationToken=false )

ユーザーアカウントを作成します。

requireConfirmationToken にfalseを指定または省略した場合、確認トークンは使われません。戻り値は確認トークンが返されます。

利用例 – User を作成し同時にログインさせる

@{
// TODO: form より userName , password を取得します
if( UserExists( userName ) )
{
ModelState.AddError( userName,”指定ユーザー名のユーザーは既に存在します。” );
}
else
{
WebSecurity.CreateAccount( userName, password );
WebSecurity.Login( userName, password );
Response.Redirect( “~/” ); // サイトトップに誘導します
}
}

利用例 – User を作成し確認トークンを電子メール送信し、URL認証する

@{
// TODO: form より userName, password, emailAddr を取得します。
if( UserExists( userName ) )
{
ModelState.AddError( userName, “指定ユーザー名のユーザーは既に存在します。” );
}
else
{
var token =WebSecurity.CreateAccount( userName, password );
/* 本文とかすべて英語にする事で日本固有のメール事情についての処理から
逃げてます。必要なエンコーディング等確認して、いい感じなメールが送れるように
した方が無難でしょう。(もしくはその辺やってくれるヘルパーが出るの待つか */
var mailMessage = new System.Net.MailMessage(
“admin@example.com”, emailAddr );
mailMessage.Subject = “welcome to example.com”;
mailMessage.Body = string.Format( @”welcome to example.com
please confirm your account.
{0}?token={1}”, Url(“~/Account/Confirm”), token );
/* メール送信サーバについての設定が web.config に必要です */
using( var client = new System.Net.SmtpClient() )
{
client.Send( mailMessage );
}
// TODO: emailAddr をデータベースに保存してください。
//          これはパスワードを忘れたユーザーとのやり取りに必要になります。
}
}
— ~/Account/Confirm.cshtml
@{
var token = Request.Query[“token”];
if( !WebSecurity.ConfirmAccount( token ) )
{
ModelState.AddError( token, “確認トークンが正しくないか有効期限が切れています”);
}
}

string CreateUserAndAccount( string userName, string password,
object propertyValues=null,
bool requireConfirmaionToken=false )

アカウントを作成すると同時にユーザー属性情報を設定します。(属性情報を取り出す方法が見当たらなかったりします) 同じ WebMatrix.WebData アセンブリ内の ExtendedMembershipProvider を利用する場合に、CreateUserAndAccoutに渡されそうな気がしますが、取り出す方法が見当たりません。というわけで、多分使い道のないメソッドだと思います。

string GeneratePasswordResetToken( string userName,
int tokenExpirationInMinutesFromNow=1440 )

指定ユーザーのパスワードの回復トークンを生成します。

パスワード回復トークンは ResetPassword メソッドのパラメータに使われます。

利用例 – パスワード確認トークンの電子メール送信と、パスワードリセット

@{
/* 本文とかすべて英語にする事で日本固有のメール事情についての処理から
逃げてます。必要なエンコーディング等確認して、いい感じなメールが送れるように
した方が無難でしょう。(もしくはその辺やってくれるヘルパーが出るの待つか */
// TODO: form から userName の取得
// TODO: 登録時に取得した userName に対応する emailAddr の取得
var token = WebSecurity.GeneratePasswordResetToken( userName );
var mailMessage = new System.Net.MailMessage(
“admin@example.com”, emailAddr );
mailMessage.Subject = “welcome to example.com”;
mailMessage.Body = string.Format( @”welcome to example.com
please confirm your account.
{0}?token={1}”, Url(“~/Account/ResetPassword”), token );
/* メール送信サーバについての設定が web.config に必要です */
using( var client = new System.Net.SmtpClient() )
{
client.Send( mailMessage );
}
}
— Account/ResetPassword.cshtml
@{
if( IsPost )
{
var token = Request.Query[“token”];
var newPassword = Request[“newPassword”];
var passwordConfirm = Request[“newPassword2”];
if( string.IsNullOrWhiteSpaces( newPassword ) )
{
ModelState.AddError( “newPassword”, “新しいパスワードを指定してください”);
}
if( newPassword!=passwordConfirm )
{
ModelState.AddError( “newPassword2”, “確認パスワードが一致しません” );
}
if( ModelState.IsValid )
{
if( WebSecurity.ResetPassword( token, newPassword ) )
{
var userId =WebSecurity.GetUserIdFromPasswordResetToken( token );
// TODO: 要カスタマイズ
// サイトテンプレート、フォトギャラリーのデフォルトのDB構造に依存しています
// _AppStart.cshtml での WebSecurityの初期化部の各パラメータに合わせて
// PhotoGallery, UserProfiles, UserId, Email の各文字列を置き換えて下さい
// WebSecurity.InitializeDatabaseConnection(
//    “PhotoGallery”, “UserProfiles”, “UserId”, “Email”, true);
var db = Database.Open( “PhotoGallery” );
var user = db.QuerySingle( “select Email
from UserProfiles where UserId=@0”,userId );
WebSecurity.Login( user.Email, newPassword );
// TODO: 要カスタマイズ部 end
Response.Redirect( “/” );
}
else
{
ModelState.AddError(“パスワードを変更できませんでした”);
}
}
}
}
<form method=”post” action=””>
<label for=”password”>新規パスワード:</label>
<input type=”password” name=”newPassword” title=”パスワード”
class=”@PhotoGallery.GetValidationClass(“password”)” />
@Html.ValidationMessage(“newPassword”)
<label for=”password”>新規パスワード確認:</label>
<input type=”password” name=”newPassword2″ title=”パスワード”
class=”@PhotoGallery.GetValidationClass(“password”)” />
@Html.ValidationMessage(“newPassword2″)
<input type=”submit” value=”登録” title=”登録” />
</form>

 

すいません、疲れました、投げていいですか?って事でこの先はメソッドシグニチャと簡単な説明な感じ。

DateTime GetCreateDate( string userName )

指定ユーザーの作成日時を返します。

DateTime GetLastPasswordFailureDate( string userName )

指定ユーザーの最終パスワード認証失敗日時を返します。

DateTime GetPasswordChangedDate( string userName )

指定ユーザーの最終パスワード変更日時を返します。

int GetPasswordFailuresSinceLastSuccess( string userName )

最終ログイン成功からのパスワード認証失敗回数を返します。

int GetUserId( string userName )

指定ユーザーのIDを返します。

int GetUserIdFromPasswordResetToken( string token )

パスワード回復トークンを元にユーザーIDを返します。

void InitializeDatabaseConnection( string connectionString,
string providerName, string userTableName,
string userIdColumn, string userNameColumn,
bool autoCreateTables )

データベース接続を初期化します。カスタムプロバイダを利用する場合にプロバイダを指定する場合にはこちらを利用します。それ以外の場合、providerName パラメータを受け取らないInitializeDatabaseConnection を利用します。

void InitializeDatabaseConnection( string connectionString,
string userTableName, string userIdColumn,
string userNameColumn, bool autoCreateTables )

データベース接続を初期化します。

利用例 – _AppStart.cshtml で以下の要領でデータベース接続を初期化します。

WebSecurity.InitializeDatabaseConnection(
“PhotoGallery”, “UserProfiles”, “UserId”, “Email”, true);

bool IsAccountLockedOut( string userName,
int allowedPasswordAttempts, TimeSpan interval )

アカウントがロックアウト状態であるか返します。

bool IsAccountLockedOut( string userName,
int allowedPasswordAttempts, int intervalInSeconds )

アカウントがロックアウト状態であるか返します。

bool IsConfirmed( string userName )

アカウントが確認済みであるか返します。

bool IsCurrentUser( string userName )

現在のユーザーが指定のユーザー名であるかを示します。

bool Login( string userName, string password,
bool persistCookie=false )

ユーザーを指定パスワードでログインします。

void Logout( )

現在ユーザーをログアウトさせます。

void RequireAuthenticatedUser()

ユーザーが認証済みでない場合 HTTP 401 (Unauthorized) ステータスコードを返し処理を打ち切ります。

void RequireRoles( params string[] roles )

ユーザーが指定ロールのすべてを持っていない場合 HTTP 401 (Unauthorized) ステータスコードを返し処理を打ち切ります。

void RequireUser( string userName )

ユーザーが指定のユーザー名でない場合 HTTP 401 (Unauthorized) ステータスコードを返し処理を打ち切ります。

void RequireUser( int userId )

ユーザーが指定の ID でない場合 HTTP 401 (Unauthorized) ステータスコードを返し処理を打ち切ります。

bool ResetPassword( string passwordResetToken,
string newPassword )

ユーザーのパスワードを指定パスワードに変更します。

bool UserExists( string userName )

userName で指定されたユーザーが存在すれば true が返されます。

静的プロパティ

int CurrentUserId { get; }

現在ユーザーのIDを返します。

string CurrentUserName { get; }

現在ユーザーのユーザー名を返します。

bool HasUserId { get; }

bool IsAuthenticated { get; }

現在ユーザーが認証済みかを返します。

静的フィールド

readonly string EnableSimpleMembershipKey