Skip to content

Instantly share code, notes, and snippets.

@GeorgDangl
Created December 24, 2017 12:39
Show Gist options
  • Save GeorgDangl/d82f33488745c37f913caff325a7f464 to your computer and use it in GitHub Desktop.
Save GeorgDangl/d82f33488745c37f913caff325a7f464 to your computer and use it in GitHub Desktop.
Appending custom claims when logging in via cookie with Asp.Net Core Identity
public class AccountController : Controller
{
[HttpPost("login")]
[AllowAnonymous]
[ProducesResponseType(204)]
[ProducesResponseType(400)]
public async Task<IActionResult> Login([FromBody] LoginPost model)
{
var user = await _userManager.FindByEmailAsync(model.Identifier)
?? await _userManager.FindByNameAsync(model.Identifier);
if (user != null)
{
var passwordIsCorrect = await _userManager.CheckPasswordAsync(user, model.Password);
if (passwordIsCorrect)
{
var customClaims = new []
{
new Claim("logged_in_day", DateTime.UtcNow.DayOfWeek.ToString())
};
await _customClaimsCookieSignInHelper.SignInUserAsync(user, model.RememberMe, customClaims);
_logger.LogInformation(1, "User logged in.");
return NoContent();
}
}
return BadRequest();
}
}
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
namespace IdentityExtensions
{
public class CustomClaimsCookieSignInHelper<TIdentityUser> where TIdentityUser : IdentityUser
{
private readonly SignInManager<TIdentityUser> _signInManager;
public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
_signInManager = signInManager;
}
public async Task SignInUserAsync(TIdentityUser user, bool isPersistent, IEnumerable<Claim> customClaims)
{
var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
if (customClaims != null && claimsPrincipal?.Identity is ClaimsIdentity claimsIdentity)
{
claimsIdentity.AddClaims(customClaims);
}
await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme,
claimsPrincipal,
new AuthenticationProperties {IsPersistent = isPersistent});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment