Skip to content

Instantly share code, notes, and snippets.

@mesuttalebi
Created November 12, 2018 07:06
Show Gist options
  • Save mesuttalebi/f907a3a15e81d3c59605b0bf38445df9 to your computer and use it in GitHub Desktop.
Save mesuttalebi/f907a3a15e81d3c59605b0bf38445df9 to your computer and use it in GitHub Desktop.
CustomClaimsPrincipalFactory
// <copyright file="CustomClaimsPrincipalFactory.cs" company="">
// Copyright (c)
// </copyright>
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Platform.Business.Interfaces;
using Platform.Domain.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using IdentityRole = Platform.Domain.Entities.IdentityRole;
namespace Platform.Business.Authorization
{
public class CustomClaimsPrincipalFactory
: UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
private readonly IUserService _userService;
public CustomClaimsPrincipalFactory(IUserService userService,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> options) : base(userManager, roleManager, options)
{
_userService = userService;
}
public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
var userRoles = ((ClaimsIdentity)principal.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value).ToList();
// add Custom claims here
var allowedIpAddresses = _userService.GetAllowedIpAddresses(user.Id, userRoles);
var ipClaims = new List<Claim>();
foreach (var ipAddress in allowedIpAddresses)
{
ipClaims.Add(new Claim(Constants.Authorization.ClaimTypes.IpAddress, ipAddress));
}
((ClaimsIdentity) principal.Identity).AddClaims(ipClaims);
return principal;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment