2

MVC5 Web アプリでは、Asp.net Identity を使用しています。ユーザーが登録すると、いくつかのクレームを追加します。それらはデータベースに保存され、ユーザーがログインすると復元されます。これは完全に機能します。ここで、パラメーター (ログイン ページのチェックボックス) に基づいて、ユーザーのログイン時に特定のクレームをユーザーに追加したいと考えています。ただし、キャッチがあります。このクレームは、そのユーザー固有のセッションにのみ存在します (同じユーザーが別のブラウザー インスタンスまたはデバイスにログオンし、チェックボックスをオンにしない場合、そのユーザーはそのクレームを持ちません)。私は使用しておらず、asp.net セッションに依存したくありません。

これを簡単に実装し、呼び出し時に Claim を追加するだけAuthenticationManager.SignInです:

private async Task SignInAsync(CustomUser user, bool isPersistent, bool myCustomTemporaryClaim)
{
    var identities = await user.GenerateUserIdentityAsync(UserManager);

    if (myCustomTemporaryClaim)
    {
        identities.AddClaim(new Claim(CustomClaimTypes.MyCustomTemporaryClaim, "true"));
    }

    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identities);
}

これはうまくいきます。ただし、VS テンプレートに付属するデフォルトの asp.net ID 実装は、30 分ごとに ID を「更新」するように構成されています。これが発生すると、カスタム クレームが失われます。だから、私が知りたいのは、asp.net IDがCookieを再生成する前に、「傍受」してカスタムクレーム値を取得することは可能ですか?

削除することはできregenerateIdentityCallbackますが、この結果がどうなるかはわかりません。

4

1 に答える 1

2

今までに何をすべきかはわかったと思いますが、他の誰かがこのスレッドに出くわした場合に備えて、AddClaim を GenerateUserIdentityAsync メソッドに移動するだけでよいと思います。次に、更新が発生して regenerateIdentityCallback が呼び出されると、クレームが再び追加されます。

条件 myCustomTemporaryClaim では、GenerateUserIdentityAsync にパラメーターを含めることができます。これを行う方法と、コールバックを変更する必要がある方法の詳細については、この投稿を参照してください: MVC Identity (2.0.1) の regenerateIdentity / validateInterval 期間後に ExpireTimeSpan が無視される

つまり(UserIdにintを使用していることに注意してください)

private async Task SignInAsync(ApplicationUser user, bool isPersistent, bool myCustomTemporaryClaim)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await user.GenerateUserIdentityAsync(UserManager, myCustomTemporaryClaim);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager, bool myCustomTemporaryClaim)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        if (myCustomTemporaryClaim)
        {
            userIdentity.AddClaim(new Claim(CustomClaimTypes.MyCustomTemporaryClaim, Convert.ToString(true)));
        }

        return userIdentity;
    }
}

ちなみに、あなたの投稿を読んでしまったのは、SignInAsync を呼び出すときにカスタム クレームを失い続けていたため、これを置き換えただけです。

var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

これとともに

var identity = await user.GenerateUserIdentityAsync(UserManager);
于 2015-03-13T13:28:05.663 に答える