//Added to save claim data in coockie
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            var yearClaim = Claims.FirstOrDefault(c => c.ClaimType == "Year");

            if (yearClaim != null)
            {
                userIdentity.AddClaim(new Claim(yearClaim.ClaimType, yearClaim.ClaimValue));
            }
            return(userIdentity);
        }
예제 #2
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager)
        {
            // Обратите внимание, что authenticationType должен совпадать с типом, определенным в CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            var warehouseIdClaim = Claims.FirstOrDefault(c => c.ClaimType == "WarehouseId");

            if (warehouseIdClaim != null)
            {
                userIdentity.AddClaim(new Claim(warehouseIdClaim.ClaimType, warehouseIdClaim.ClaimValue));
            }
            return(userIdentity);
        }
예제 #3
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <BkUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            var dbsidClaim = Claims.FirstOrDefault(c => c.ClaimType == Common.Constants.DbsidClaimType);

            if (dbsidClaim != null)
            {
                userIdentity.AddClaim(new Claim(dbsidClaim.ClaimType, dbsidClaim.ClaimValue));
            }

            return(userIdentity);
        }
예제 #4
0
        private bool TryGetClaim(string key, out string claim)
        {
            bool b = false;

            claim = String.Empty;
            var found = Claims.FirstOrDefault(x => x.Type.Equals(key, StringComparison.OrdinalIgnoreCase));

            if (found != null && !String.IsNullOrEmpty(found.Value))
            {
                claim = found.Value;
                b     = true;
            }
            return(b);
        }
예제 #5
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            var YearClaim = Claims.FirstOrDefault(c => c.ClaimType == "Year");

            if (YearClaim != null)
            {
                userIdentity.AddClaim(new Claim(YearClaim.ClaimType, YearClaim.ClaimValue));
            }

            return(userIdentity);
        }
예제 #6
0
        private (IdentityRole, IdentityClaim, IdentityExternalLogin, IdentityUser) CreateTestData(IGraphClient client,
                                                                                                  UserStore <IdentityUser> us, RoleStore <IdentityRole> rs)
        {
            var user = CreateUser(client, us);
            var role = CreateRole(client, rs);

            us.AddClaimsAsync(user, new[] { new Claim("TEST_CLAIM", "TEST_CLAIM_VALUE") }, default).Wait();
            us.AddLoginAsync(user, new UserLoginInfo("GOOGLE", "KEY", "XGOOGLE"), default).Wait();
            us.AddToRoleAsync(user, role.Name, default).Wait();
            var res = us.UpdateAsync(user, default).Result;

            Assert.True(res.Succeeded);
            user = FetchTestUser(client, us);
            return(role, user.Claims.FirstOrDefault(), user.Logins.FirstOrDefault(), user);
        }
예제 #7
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager)
        {
            // Обратите внимание, что authenticationType должен совпадать с типом, определенным в CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Здесь добавьте утверждения пользователя
            var istClaim = Claims.FirstOrDefault(c => c.ClaimType == "Istoria");

            if (istClaim != null)
            {
                userIdentity.AddClaim(new Claim(istClaim.ClaimType, istClaim.ClaimValue));
            }

            //userIdentity.AddClaim(new Claim("Istoria", this.Istor.ToString()));
            return(userIdentity);
        }
예제 #8
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            userIdentity.AddClaim(new Claim(ClaimTypes.Gender, this.Gender));
            userIdentity.AddClaim(new Claim("age", this.Age.ToString()));
            var yearClaim = Claims.FirstOrDefault(x => x.ClaimType == "Year");

            if (yearClaim != null)
            {
                userIdentity.AddClaim(new Claim(yearClaim.ClaimType, yearClaim.ClaimValue));
            }

            return(userIdentity);
        }
예제 #9
0
        /// <summary>
        /// Check if the badge has at least one of the passed claims
        /// </summary>
        /// <param name="claims">List of claims separated by commas</param>
        /// <returns></returns>
        public bool HasClaims(string claims)
        {
            bool result = false;

            if (claims != null)
            {
                if (claims.Contains(","))
                {
                    foreach (var item in claims.Split(','))
                    {
                        if (Claims.FirstOrDefault(x => x == item) != default(string))
                        {
                            result = true;
                            break;
                        }
                    }
                }
                else
                {
                    result = Claims.FirstOrDefault(x => x == claims) != default(string);
                }
            }
            return(result);
        }
예제 #10
0
        public virtual IdentityUserClaim FindClaim([NotNull] Claim claim)
        {
            Check.NotNull(claim, nameof(claim));

            return(Claims.FirstOrDefault(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value));
        }
예제 #11
0
        /// <summary>
        /// Checks whether Identity has the role.
        /// </summary>
        /// <param name="roleName">Role name.</param>
        /// <returns>True if Identity has the role.</returns>
        public bool IsInRole(string roleName)
        {
            var roleClaim = Claims?.FirstOrDefault(c => c.Type == ClaimTypes.Role && string.Equals(c.Value, roleName, StringComparison.OrdinalIgnoreCase));

            return(roleClaim != null);
        }
예제 #12
0
 public string GetClaim(string type)
 {
     return(Claims.FirstOrDefault(p => p.Type == type)?.Value);
 }
예제 #13
0
 private string GetClaimValue(string claimType) => Claims.FirstOrDefault(x => x.Type == claimType)?.Value;
예제 #14
0
 public virtual ClientClaim FindClaim(string value, string type)
 {
     return(Claims.FirstOrDefault(c => c.Type == type && c.Value == value));
 }
예제 #15
0
        /// <summary>
        /// Validates the token
        /// </summary>
        /// <param name="expectedAudience">The valid audience value to check</param>
        /// <returns></returns>
        public async Task <SsoTokenValidationResult> Validate()
        {
            ServiceStack.Logging.ILog log    = ServiceStack.Logging.LogManager.GetLogger(typeof(AddInSsoToken));
            SsoTokenValidationResult  result = new SsoTokenValidationResult();

            log.Debug("before get well known");
            OpenIdConnectConfiguration config = await GetOIDConnectConfig(_wellKnownUri);


            // Issuer will always be Azure, but it will contain the tenant ID of the
            // Office 365 organization the user belongs to. We can get that from the "tid" claim

            var preferredName = Claims.FirstOrDefault(claim => claim.Type == "email");

            if (preferredName == null)
            {
                preferredName = Claims.FirstOrDefault(claim => claim.Type == "upn");
            }

            if (preferredName == null)
            {
                preferredName = Claims.FirstOrDefault(claim => claim.Type == "preferred_username");
            }

            if (preferredName == null)
            {
                result.Message = "Preferred name not found.";
                return(result);
            }


            var exp = Claims.FirstOrDefault(claim => claim.Type == "exp");

            if (exp != null)
            {
                result.Exp = Int64.Parse(exp.Value);
            }


            // Use System.IdentityModel.Tokens.Jwt library to validate the token
            JwtSecurityTokenHandler   tokenHandler = new JwtSecurityTokenHandler();
            TokenValidationParameters tvp          = new TokenValidationParameters();

            tvp.ValidateIssuer           = true;
            tvp.ValidIssuer              = GetIssuerUri();
            tvp.ValidateAudience         = true;
            tvp.ValidAudience            = _clientId;
            tvp.ValidateIssuerSigningKey = true;
            tvp.IssuerSigningKeys        = config.SigningKeys as IEnumerable <Microsoft.IdentityModel.Tokens.SecurityKey>;
            tvp.ValidateLifetime         = true;


            try
            {
                var claimsPrincipal = tokenHandler.ValidateToken(RawData, tvp, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken);
                System.Security.Claims.ClaimsPrincipal.ClaimsPrincipalSelector = () => {
                    (claimsPrincipal.Identity as ClaimsIdentity).BootstrapContext = new BootstrapContext(this.RawData);
                    return(claimsPrincipal);
                };

                // If no exception, all standard checks passed
                result.IsValid        = true;
                result.LifetimeResult = result.SignatureResult = result.AudienceResult = result.IssuerResult = "passed";
                result.PreferredName  = preferredName.Value;
            }
            catch (SecurityTokenInvalidAudienceException ex)
            {
                result.AudienceResult = "failed";
                result.Message        = ex.Message;
            }
            catch (SecurityTokenInvalidIssuerException ex)
            {
                result.IssuerResult = "failed";
                result.Message      = ex.Message;
            }
            catch (SecurityTokenInvalidLifetimeException ex)
            {
                result.LifetimeResult = "failed";
                result.Message        = ex.Message;
            }
            catch (Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException ex)
            {
                result.LifetimeResult = "failed";
                result.Message        = ex.Message;
            }
            catch (SecurityTokenInvalidSignatureException ex)
            {
                result.SignatureResult = "failed";
                result.Message         = ex.Message;
            }
            catch (Microsoft.IdentityModel.Tokens.SecurityTokenValidationException ex)
            {
                result.Message = ex.Message;
            }


            return(result);
        }
예제 #16
0
        /// <summary>
        /// Validates the token
        /// </summary>
        /// <param name="expectedAudience">The valid audience value to check</param>
        /// <returns></returns>
        public async Task <SsoTokenValidationResult> Validate(string expectedAudience)
        {
            SsoTokenValidationResult result = new SsoTokenValidationResult();

            // Since add-in SSO tokens are issued by Azure, we can use the
            // well-known OpenID config to get signing keys
            string openIdConfig = $"https://login.microsoftonline.com/dd30c61c-1361-4509-82d6-fab96f7102a2/v2.0/.well-known/openid-configuration";

            ConfigurationManager <OpenIdConnectConfiguration> configManager =
                new ConfigurationManager <OpenIdConnectConfiguration>(openIdConfig, new OpenIdConnectConfigurationRetriever());

            OpenIdConnectConfiguration config = await configManager.GetConfigurationAsync();

            // Issuer will always be Azure, but it will contain the tenant ID of the
            // Office 365 organization the user belongs to. We can get that from the "tid" claim
            var tenantIdClaim = Claims.FirstOrDefault(claim => claim.Type == "tid");

            if (tenantIdClaim == null)
            {
                result.Message = "Token is malformed, missing tid claim.";
                return(result);
            }

            var oidClaim = Claims.FirstOrDefault(claim => claim.Type == "oid");

            if (oidClaim == null)
            {
                result.Message = "Token is malformed, missing oid claim.";
                return(result);
            }

            var preferredName = Claims.FirstOrDefault(claim => claim.Type == "preferred_username");

            if (preferredName == null)
            {
                preferredName = Claims.FirstOrDefault(claim => claim.Type == "upn");
            }

            if (preferredName == null)
            {
                result.Message = "Preferred name not found.";
                return(result);
            }

            string expectedIssuer = string.Format("https://login.microsoftonline.com/{0}/v2.0", tenantIdClaim.Value);

            // Use System.IdentityModel.Tokens.Jwt library to validate the token
            JwtSecurityTokenHandler   tokenHandler = new JwtSecurityTokenHandler();
            TokenValidationParameters tvp          = new TokenValidationParameters();

            tvp.ValidateIssuer           = true;
            tvp.ValidIssuer              = expectedIssuer;
            tvp.ValidateAudience         = true;
            tvp.ValidAudience            = expectedAudience;
            tvp.ValidateIssuerSigningKey = true;
            tvp.IssuerSigningKeys        = config.SigningKeys as IEnumerable <Microsoft.IdentityModel.Tokens.SecurityKey>;
            tvp.ValidateLifetime         = true;


            try
            {
                var claimsPrincipal = tokenHandler.ValidateToken(RawData, tvp, out Microsoft.IdentityModel.Tokens.SecurityToken validatedToken);
                System.Security.Claims.ClaimsPrincipal.ClaimsPrincipalSelector = () => {
                    (claimsPrincipal.Identity as ClaimsIdentity).BootstrapContext = new BootstrapContext(this.RawData);
                    return(claimsPrincipal);
                };

                // If no exception, all standard checks passed
                result.IsValid        = true;
                result.LifetimeResult = result.SignatureResult = result.AudienceResult = result.IssuerResult = "passed";

                result.ComputedUserId = GenerateUserId(oidClaim.Value, tenantIdClaim.Value);
                result.PreferredName  = preferredName.Value;
            }
            catch (SecurityTokenInvalidAudienceException ex)
            {
                result.AudienceResult = "failed";
                result.Message        = ex.Message;
            }
            catch (SecurityTokenInvalidIssuerException ex)
            {
                result.IssuerResult = "failed";
                result.Message      = ex.Message;
            }
            catch (SecurityTokenInvalidLifetimeException ex)
            {
                result.LifetimeResult = "failed";
                result.Message        = ex.Message;
            }
            catch (Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException ex)
            {
                result.LifetimeResult = "failed";
                result.Message        = ex.Message;
            }
            catch (SecurityTokenInvalidSignatureException ex)
            {
                result.SignatureResult = "failed";
                result.Message         = ex.Message;
            }
            catch (Microsoft.IdentityModel.Tokens.SecurityTokenValidationException ex)
            {
                result.Message = ex.Message;
            }

            return(result);
        }
예제 #17
0
        public T GetClaimValue <T>(string type, T defaultValue = default(T))
        {
            var claim = Claims.FirstOrDefault(c => c.Type == type);

            return(claim != null ? (T)Convert.ChangeType(claim.Value, typeof(T)) : default(T));
        }
예제 #18
0
 public ClientClaimDto FindClaim(string value, string type)
 {
     return Claims.FirstOrDefault(c => c.Type == type && c.Value == value);
 }
예제 #19
0
 private string FindFirst(string claimType)
 {
     return(Claims.FirstOrDefault(claim => claim.Type == claimType)?.Value);
 }
예제 #20
0
 private string GetClaim(string claimType)
 {
     return(Claims.FirstOrDefault(x => x.Type == claimType).Value);
 }
예제 #21
0
 /// <summary>
 /// Gets a claim, if available
 /// </summary>
 /// <param name="claimKey">The claim key to return. Claims are NOT case sensitive</param>
 /// <returns>A claim based on the key</returns>
 public IIpClaim GetClaim(string claimKey)
 {
     return(Claims.FirstOrDefault(c => c.ClaimKey.Equals(claimKey, StringComparison.OrdinalIgnoreCase)));
 }