2016-12-06 67 views
1

我想將內容保存到「身份」生成的Cookie中。我目前正在使用文檔中的默認Identity設置。使用ASP.NET Core Identity在Cookie中保存標記

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); 

看來這是行不通的。因爲該cookie尚未創建。 '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>); 

在這種情況下,我需要建立一個自己'用戶主管'。我更願意在這個問題上利用「身份」。

那麼可以結合這個嗎? 如果不是這種情況,我該如何生成claimprincipal。

無需「映射」每一項索賠。

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行代碼是最重要的。

相關問題