Пример #1
0
        private string CreateEncodedJwt(ClaimsIdentity claimsIdentity)
        {
            var now = DateTime.UtcNow;

            // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
            // You can add other claims here, if you want:
            var claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, claimsIdentity.Name),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64),
            };

            var claimsIdentityRoles = claimsIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToArray();
            var allClaims           = claims.Concat(claimsIdentityRoles).ToArray();

            // Create the JWT and write it to a string
            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: allClaims,
                notBefore: now,
                expires: now.Add(_options.Expiration),
                signingCredentials: _options.SigningCredentials);

            var jwtEncodedToken = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(jwtEncodedToken);
        }
Пример #2
0
        public TokenEntity GenerateToken(params Claim[] otherClaims)
        {
            var now = DateTime.Now;
            IEnumerable <Claim> claims = new Claim[]
            {
                new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64)
            };

            if (otherClaims != null)
            {
                claims = claims.Concat(otherClaims);
            }
            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: _options.Expiration,
                signingCredentials: _options.SigningCredentials);
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            return(new TokenEntity()
            {
                AccessToken = encodedJwt,
                ExpiresIn = (int)_options.ValidFor.TotalSeconds
            });
        }
Пример #3
0
        public string Create(User user, string[] roles)
        {
            var roleClaims = roles.Select(role => new Claim(ClaimTypes.Role, role));
            var userClaims = new Claim[]
            {
                new Claim(UserIdClaim, user.Id.ToString()),
                new Claim(UsernameClaim, user.Username),
            };
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(userClaims.Concat(roleClaims)),
                Expires            = DateTime.UtcNow.AddMinutes(config.ExpirationInMinutes),
                SigningCredentials = new SigningCredentials(
                    new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(config.SharedSecret !)),
                    SecurityAlgorithms.HmacSha256Signature),
                Issuer   = config.Issuer,
                Audience = config.Issuer
            };

            var tokenHandler  = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(securityToken));
        }
    }
Пример #4
0
        public async Task <string> GenerateUserTokenAsync(User user)
        {
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jWTOptions.Secret));
            var roles = await _roleQueryService.GetRolesByUserId(user.Id);

            IEnumerable <Claim> claims = new Claim[] {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Login),
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddDays(5)).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
            };

            claims = claims.Concat(roles.Select(s => new Claim(ClaimTypes.Role, s.Name)));
            var token = new JwtSecurityToken(
                issuer: _jWTOptions.Issuer,
                audience: _jWTOptions.Audience,
                claims: claims,
                notBefore: DateTime.Now,
                expires: DateTime.Now.AddDays(5),
                signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
                );
            string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return(jwtToken);
        }
Пример #5
0
        private JwtSecurityToken GetNewToken(string subjectClaimValue, params Claim[] customClaims)
        {
            var now = DateTime.UtcNow;

            var claims = new Claim[]
            {
                // Subject - https://tools.ietf.org/html/rfc7519#section-4.1.2
                new Claim(JwtRegisteredClaimNames.Sub, subjectClaimValue),
                // JWT ID - https://tools.ietf.org/html/rfc7519#section-4.1.7
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                // Issued At - https://tools.ietf.org/html/rfc7519#section-4.1.6
                new Claim(JwtRegisteredClaimNames.Iat, new DateTimeOffset(now).ToUniversalTime().ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64),
            };

            if (customClaims != null)
            {
                claims = claims.Concat(customClaims).ToArray();
            }

            var jwt = new JwtSecurityToken(
                issuer: _options.Issuer,
                audience: _options.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(TimeSpan.FromMinutes(_options.Expiration)),
                signingCredentials: GetCredentials());

            return(jwt);
        }
        private ClaimsPrincipal PrincipleFromUser(IUser user)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Identity),
                new Claim(ClaimTypes.Authentication, "true", ClaimValueTypes.Boolean)
            };
            var identity = new ClaimsIdentity(claims.Concat(user.Roles.Select(r => new Claim(ClaimTypes.Role, r))));

            return(new ClaimsPrincipal(identity));
        }
Пример #7
0
        public UserWithoutPasswordDto Authenticate(UsernamePasswordDto dto)
        {
            var user = this.context.Users.SingleOrDefault(u => u.Username == dto.Username);

            if (user == null)
            {
                throw new DotaException(Constants.IncorrectUsernamePassword);
            }

            if (!VerifyPasswordHash(dto.Password, user.PasswordHash, user.PasswordSalt))
            {
                throw new DotaException(Constants.IncorrectUsernamePassword);
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            var key          = Encoding.ASCII.GetBytes(this.appSettings.Secret);

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.Name, user.Id.ToString())
            };

            claims = claims.Concat(user.Roles.Select(r => new Claim(ClaimTypes.Role, r.Role.Name))).ToArray();

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity
                          (
                    claims
                          ),
                Expires            = DateTime.UtcNow.AddMinutes(30),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var userDto = new UserWithoutPasswordDto
            {
                Id        = user.Id,
                Email     = user.Email,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                Username  = user.Username,
                Token     = tokenHandler.WriteToken(token)
            };

            return(userDto);
        }
Пример #8
0
        public static string GenerateExpectedAccessToken(JwtSecurityToken token, string audience, string accessKey, IEnumerable <Claim> customClaims = null)
        {
            var requestId = token.Claims.FirstOrDefault(claim => claim.Type == Constants.ClaimType.Id)?.Value;

            var userClaimType = JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap[ClaimTypes.NameIdentifier];
            var userId        = token.Claims.FirstOrDefault(claim => claim.Type == userClaimType)?.Value;

            var claims = new Claim[] { new Claim(ClaimTypes.NameIdentifier, userId) };

            if (customClaims != null)
            {
                claims = claims.Concat(customClaims).ToArray();
            }

            var tokenString = GenerateJwtBearer(audience, claims, token.ValidTo,
                                                token.ValidFrom,
                                                token.ValidFrom,
                                                accessKey,
                                                requestId);

            return(tokenString);
        }
        public async Task <ActionResult> Post(AuthenticationRequest authRequest,
                                              [FromServices] IJwtSigningEncodingKey signingEncodingKey)
        {
            //Проверка данных пользователя
            if (authRequest.Email == null || authRequest.Password == null)
            {
                var errorText = "Invalid email or password";
                Response.StatusCode = 400;
                return(BadRequest(errorText));
            }

            var user = await _userManager.FindByEmailAsync(authRequest.Email);

            if (user == null)
            {
                var errorText = "Invalid email";
                Response.StatusCode = 400;
                return(BadRequest(errorText));
            }

            var passwordOk = await _userManager.CheckPasswordAsync(user, authRequest.Password);

            if (!passwordOk)
            {
                var errorText = "Invalid password";
                Response.StatusCode = 400;
                return(BadRequest(errorText));
            }

            var userClaims = await _userManager.GetClaimsAsync(user);

            //Создаем утверждения для токена

            var claims = new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, authRequest.Email),
            };

            //Генерируем JWT

            var token = new JwtSecurityToken(
                issuer: "ThothCore",
                audience: "ThothCoreClient",
                claims: claims.Concat(userClaims).ToArray(),
                expires: DateTime.Now.AddMinutes(5),
                signingCredentials: new SigningCredentials(signingEncodingKey.GetKey(), signingEncodingKey.SigningAlgorithm)
                );

            string       jwtToken     = new JwtSecurityTokenHandler().WriteToken(token);
            const string jwtShemeName = "JwtBearer";
            await _userManager.SetAuthenticationTokenAsync(user, jwtShemeName, jwtShemeName, jwtToken);


            var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

            Response.Cookies.Append(
                "accessToken",
                tokenString,
                new CookieOptions()
            {
                Path = "/"
            }
                );

            return(new JsonResult(new
            {
                access_token = jwtToken,
                username = user.Name
            }));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"AMS v3 Function - CreateJwtToken was triggered!");

            string  requestBody = new StreamReader(req.Body).ReadToEnd();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            string streaminglocatorName = data.streamingLocatorName;
            string contentKeyPolicyName = data.contentKeyPolicyName;
            string accountName          = data.accountName;
            string resourceGroup        = data.resourceGroup;

            MediaServicesConfigWrapper amsconfig = new MediaServicesConfigWrapper();
            string token = null;

            try
            {
                IAzureMediaServicesClient client = MediaServicesHelper.CreateMediaServicesClientAsync(amsconfig);

                var response         = client.StreamingLocators.ListContentKeys(resourceGroup, accountName, streaminglocatorName);
                var contentKeyId     = response.ContentKeys.First().Id.ToString();
                var policyProperties = client.ContentKeyPolicies.GetPolicyPropertiesWithSecrets(resourceGroup, accountName, contentKeyPolicyName);

                var ckrestriction   = (ContentKeyPolicyTokenRestriction)policyProperties.Options.FirstOrDefault()?.Restriction;
                var symKey          = (ContentKeyPolicySymmetricTokenKey)ckrestriction.PrimaryVerificationKey;
                var tokenSigningKey = new SymmetricSecurityKey(symKey.KeyValue);

                SigningCredentials cred = new SigningCredentials(
                    tokenSigningKey,
                    // Use the  HmacSha256 and not the HmacSha256Signature option, or the token will not work!
                    SecurityAlgorithms.HmacSha256,
                    SecurityAlgorithms.Sha256Digest);

                Claim[] claims = new Claim[] {
                    new Claim(ContentKeyPolicyTokenClaim.ContentKeyIdentifierClaim.ClaimType, contentKeyId)
                };

                // 2021.08.24 [email protected]
                // Add maxuses for my demo purpose
                //
                Claim[] maxuse = new Claim[] {
                    new Claim("urn:microsoft:azure:mediaservices:maxuses", "2")
                };

                claims = claims.Concat(maxuse).ToArray();

                //

                foreach (var cl in claims)
                {
                    Console.WriteLine(cl.Type + " " + cl.Value);
                }

                JwtSecurityToken jwtToken = new JwtSecurityToken(
                    issuer: ckrestriction.Issuer,
                    audience: ckrestriction.Audience,
                    claims: claims,
                    notBefore: DateTime.Now.AddMinutes(-5),
                    expires: DateTime.Now.AddMinutes(60),
                    signingCredentials: cred);

                JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                token = $"Bearer {handler.WriteToken(jwtToken)}";
            }
            catch (ApiErrorException e)
            {
                log.LogError($"ERROR: AMS API call failed with error code: {e.Body.Error.Code} and message: {e.Body.Error.Message}");
                return(new BadRequestObjectResult("AMS API call error: " + e.Message + "\nError Code: " + e.Body.Error.Code + "\nMessage: " + e.Body.Error.Message));
            }
            catch (Exception e)
            {
                log.LogError($"ERROR: Exception with message: {e.Message}");
                return(new BadRequestObjectResult("Error: " + e.Message));
            }

            return((ActionResult) new OkObjectResult(new
            {
                token = token
            }));
        }