Example #1
0
        public async Task <ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
        {
            var identity = principal.Identity as ClaimsIdentity;

            foreach (var claim in identity.Claims.ToArray())
            {
                if (exludedClaims.Contains(claim.Type))
                {
                    identity.RemoveClaim(claim);
                }
            }

            this.Client = new Client
            {
                Id    = principal.FindFirstValue(ApiKeyAuthentication.ClaimNames.ClientId),
                Scope = principal.FindFirstValue(ApiKeyAuthentication.ClaimNames.ClientScope),
                Url   = principal.FindFirstValue(ApiKeyAuthentication.ClaimNames.ClientUrl)
            };

            if (principal.Identity.AuthenticationType == ApiKeyAuthentication.AuthenticationScheme)
            {
                return(principal);
            }

            string sub = principal.FindFirstValue(JwtRegisteredClaimNames.Sub);

            string name = principal.FindFirstValue("name");

            _user = await _identitySvc.Load(sub);

            if (_user != null)
            {
                AddOrUpdateClaim(identity, JwtRegisteredClaimNames.NameId, _user.Id.ToString());
                AddOrUpdateClaim(identity, "name", _user.Name);
                AddOrUpdateClaim(identity, "role", _user.Role.ToString());

                return(principal);
            }

            // prevents auto-registration from happening more than once
            await semaphoreSlim.WaitAsync();

            try
            {
                // try again after getting passed semaphore
                _user = await _identitySvc.Load(sub);

                if (_user == null)
                {
                    _user = await _identitySvc.Add(new User {
                        GlobalId = sub,
                        Name     = name
                    });
                }
            }

            finally
            {
                semaphoreSlim.Release();
            }

            AddOrUpdateClaim(identity, JwtRegisteredClaimNames.NameId, _user.Id.ToString());
            AddOrUpdateClaim(identity, "name", _user.Name);
            AddOrUpdateClaim(identity, "role", _user.Role.ToString());

            return(principal);
        }