2016-12-06 8 views
1

「アイデンティティ」生成クッキー内に何かを保存したいと思います。私は現在、ドキュメントからデフォルトのアイデンティティ設定を使用しています。ASP.NETコアIDを持つクッキーにトークンを保存

Startup.cs

services.Configure<IdentityOptions>(options => 
{ 
    // User settings 
    options.User.RequireUniqueEmail = true; 

    // Cookie settings 
    options.Cookies.ApplicationCookie.AuthenticationScheme = "Cookies"; 
    options.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(1); 
    options.Cookies.ApplicationCookie.SlidingExpiration = true; 
    options.Cookies.ApplicationCookie.AutomaticAuthenticate = true; 
    options.Cookies.ApplicationCookie.LoginPath = "/Account"; 
    options.Cookies.ApplicationCookie.LogoutPath = "/Account/Logout"; 
}); 

AccountController.cs

var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, true, true); 

if (result.Succeeded) 
{ 
    _logger.LogInformation(1, "User logged in."); 

    var tokens = new List<AuthenticationToken> 
    { 
     new AuthenticationToken {Name = "Test", Value = "Test"}, 
    }; 


    var info = await HttpContext.Authentication.GetAuthenticateInfoAsync("Cookies"); 
    info.Properties.StoreTokens(tokens); 

動作しないようです。クッキーはまだ作成されていないためです。 'Info'変数は空です。

私が使用して、それを解決できる 'CookieMiddleware'

Startup.cs

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationScheme = "Cookies", 
    ExpireTimeSpan = TimeSpan.FromHours(1), 
    SlidingExpiration = true, 
    AutomaticAuthenticate = true, 
    LoginPath = "/Account", 
    LogoutPath = "/Account/Logout", 
}); 

しかし、私はこの場合

await HttpContext.Authentication.SignInAsync("Cookies", <userPrincipal>); 

を私は自分自身構築する必要があります使用する必要があるよりも、 'ユーザープリンシパル'。そして、私はこの問題に対して「アイデンティティ」を活用することを好む。

これを組み合わせることは可能ですか? これが当てはまらない場合は、どのようにすれば良い方法でclaimsprincipalを生成できますか?

すべてのクレームを「マップ」する必要はありません。だから、

List<Claim> userClaims = new List<Claim> 
{ 
    new Claim("UserId", Convert.ToString(user.Id)), 
    new Claim(ClaimTypes.Name, user.UserName), 
    // TODO: Foreach over roles 
}; 

ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(userClaims)); 
await HttpContext.Authentication.SignInAsync("Cookies", principal); 

のようなもの:

ClaimsPrincipal pricipal = new ClaimsPrincipal(user.Claims); 

user.ClaimsはタイプIdentityUserClaimのとないタイプSecurity.Claims.Claimであるので、これは動作しません。

読んでいただきありがとうございます。 は良い一日、

は誠意をこめて、ブレヒト

答えて

2

は、私は私の問題を解決するために管理しています。

私は 'signInManager'の内部にある同じ機能を記述しました。しかし、私自身の認証プロパティを追加する。実際にクッキーの内側に何か(トークン)を保存

var result = await _signInManager.PasswordSignInAsync(user, model.Password, true, true); 
if (result.Succeeded) 
{ 
    await AddTokensToCookie(user, model.Password); 
    return RedirectToLocal(returnUrl); 
} 
if (result.RequiresTwoFactor) 
{ 
    // Ommitted 
} 
if (result.IsLockedOut) 
{ 
    // Ommitted 
} 

コード:コードの

private async Task AddTokensToCookie(ApplicationUser user, string password) 
{ 
    // Retrieve access_token & refresh_token 
    var disco = await DiscoveryClient.GetAsync(Environment.GetEnvironmentVariable("AUTHORITY_SERVER") ?? "http://localhost:5000"); 

    if (disco.IsError) 
    { 
     _logger.LogError(disco.Error); 
     throw disco.Exception; 
    } 

    var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret"); 
    var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync(user.Email, password, "offline_access api1"); 

    var tokens = new List<AuthenticationToken> 
    { 
     new AuthenticationToken {Name = OpenIdConnectParameterNames.AccessToken, Value = tokenResponse.AccessToken}, 
     new AuthenticationToken {Name = OpenIdConnectParameterNames.RefreshToken, Value = tokenResponse.RefreshToken} 
    }; 

    var expiresAt = DateTime.UtcNow + TimeSpan.FromSeconds(tokenResponse.ExpiresIn); 
    tokens.Add(new AuthenticationToken 
    { 
     Name = "expires_at", 
     Value = expiresAt.ToString("o", CultureInfo.InvariantCulture) 
    }); 

    // Store tokens in cookie 
    var prop = new AuthenticationProperties(); 
    prop.StoreTokens(tokens); 
    prop.IsPersistent = true; // Remember me 

    await _signInManager.SignInAsync(user, prop); 
} 

最後の4行は、最も重要なものです。

関連する問題