2017-01-26 21 views
5

ASP.NET Core Webアプリケーションのコントローラで、クライアントに格納されているCookieチケットのユーザーとクレームを更新します。ASP.NetコアIDのユーザークッキーチケットを更新する

クライアントは認証され、承認され、ASP.NET Core Identityはこの情報をCookieチケットに保存します。これにより、Cookie内のデータを更新するいくつかのコントローラアクションが追加されます。

SignInManagerは、RefreshSignInAsyncをリフレッシュする機能を持ちますが、パラメータとしてHttpContext.Userを受け入れません。

[HttpPost("[action]")] 
[Authorize] 
public async Task<IActionResult> Validate() 
{ 
    // todo: update the Client Cookie 
    await _signInManager.RefreshSignInAsync(User); // wrong type 
} 

どのようにしてクッキーをリフレッシュできますか?

+0

さて、あなたのコントローラでこのようにそれを使用します'HttpContext.User'にはプリンシパル(' ClaimsPrincipal'、アイデンティティとクレーム)。 SignInManager Identityを設定するのに使用したユーザタイプに依存する 'TUser'を受け取ります。トークンからユーザーIDを取得し、ユーザーを取得して更新してください。 – Tseng

答えて

7
public static class HttpContextExtenssions 
{ 
    public static async Task RefreshLoginAsync(this HttpContext context) 
    { 
     if (context.User == null) 
      return; 

     // The example uses base class, IdentityUser, yours may be called 
     // ApplicationUser if you have added any extra fields to the model 
     var userManager = context.RequestServices 
      .GetRequiredService<UserManager<IdentityUser>>(); 
     var signInManager = context.RequestServices 
      .GetRequiredService<SignInManager<IdentityUser>>(); 

     IdentityUser user = await userManager.GetUserAsync(context.User); 

     if(signInManager.IsSignedIn(context.User)) 
     { 
      await signInManager.RefreshSignInAsync(user); 
     } 
    } 
} 

はその後、その後、アクションフィルタ

public class RefreshLoginAttribute : ActionFilterAttribute 
{ 
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) 
    { 
     await context.HttpContext.RefreshLoginAsync(); 

     await next(); 
    } 
} 

であなたのコントローラ

[HttpPost("[action]")] 
[Authorize] 
public async Task<IActionResult> Validate() 
{ 
    await HttpContext.RefreshLoginAsync(); 
} 

それとも抽象的にそれを使用

[HttpPost("[action]")] 
[Authorize] 
[RefreshLogin] // or simpler [Authorize, RefreshLogin] 
public async Task<IActionResult> Validate() 
{ 
    // your normal controller code 
} 
+0

ニース - 一つのこととして、userManager.GetUserAsyncは、代わりにIdentityUser型を返しますが、代わりにIdentityRoleEntityを返します。これは、RefreshSignInAsyncでパラメータとして使用することはできません。 – Sam

+0

'IdentityRoleEntity'はどこから来たのですか?アイデンティティの一部ではないようです。あなたのクラスは 'Identity'から派生していますか?私はUserManagerがIdentityから来ているのかどうか聞いてくるのは、その上のジェネリックパラメータはデフォルトモデルの 'UserManager 'や 'UserManager 'なのか、 。 – Tseng

+0

ああ、はい - 私は自分のエンティティタイプで 'IdentityUser'を置き換えずに、あなたのサンプルコード' var userManager = context.RequestServices .GetRequiredService >(); 'を使用しました。 代わりに、 'var userManager = context.RequestServices .GetRequiredService >();'を使う必要がありました。 – Sam

関連する問題