Ejemplo n.º 1
0
        /// <summary>
        ///     Creates a basic login result.
        ///     Adds user role claims to Jwt payload
        ///     NOTE: If you duplicate a key in the additionalPayload, this will error.
        /// </summary>
        /// <param name="authUser"></param>
        /// <param name="client"></param>
        /// <param name="config"></param>
        /// <param name="additionalPayload"></param>
        /// <returns></returns>
        protected LoginResult GetBaseLoginResult(AuthUser authUser, AuthClient client, JwtConfig config, IDictionary <string, string> additionalPayload = null)
        {
            config.RefreshMinutes = client.RefreshTokenMinutes; // MUST set refresh minutes by client
            var now = DateTime.UtcNow;
            IDictionary <string, string[]> payload = CreateJwtPayload(authUser, client);

            if (additionalPayload != null)
            {
                foreach (var kv in additionalPayload)
                {
                    payload.Add(kv.Key, new[] { kv.Value });
                }
            }
            // add ossied time for easier parsing
            payload.Add(OwinKeys.Ticks, new[] { now.Ticks.ToString() });

            // add claims
            bool hasClaims  = (authUser.UserRole?.UserRoleClaims != null);
            var  claimFlags = new Dictionary <int, int>();

            if (hasClaims)
            {
                foreach (var cgroup in authUser.UserRole.UserRoleClaims.GroupBy(cv => cv.ClaimTypeId))
                {
                    int claimValues = cgroup.Aggregate(0, (v, urc) => v | urc.ClaimValueId); // | them together
                    claimFlags.Add(cgroup.Key, claimValues);
                    payload[ClaimsHelper.SetTypePrefix(cgroup.Key)] = new [] { claimValues.ToString() };
                }
            }

            string accessToken  = JsonWebToken.CreateAccessToken(config, now, payload);
            string refreshToken = JsonWebToken.CreateRefreshToken(config, now, payload);
            string csrfToken    = CsrfToken.Create(accessToken);
            Guid   refreshGuid  = AuthService.CreateToken(authUser.Id, client.Id, now, config.RefreshMinutes, refreshToken);

            return(new LoginResult
            {
                AuthUserId = authUser.Id,
                ClaimFlags = claimFlags,
                IssuedUtc = now,
                ExpiresUtc = now.AddMinutes(config.AccessMinutes),
                RefreshTokenIdentifier = refreshGuid.ToString(),
                Jwt = accessToken,
                CsrfToken = csrfToken
            });
        }