Esempio n. 1
0
        public string Generate(string user, CliendId client)
        {
            byte[] privateKeyRaw = Convert.FromBase64String(Constants.PrivateKey);

            // creating the RSA key
            var provider = new RSACryptoServiceProvider();

            provider.ImportPkcs8PrivateKey(new ReadOnlySpan <byte>(privateKeyRaw), out _);
            var rsaSecurityKey = new RsaSecurityKey(provider);

            // Generating the token
            DateTime now = DateTime.UtcNow;

            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, client.Id),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user),
                new Claim(JwtRegisteredClaimNames.NameId, client.ConnectionId),
            };

            var handler = new JwtSecurityTokenHandler();

            var token = new JwtSecurityToken
                        (
                App,
                client.Id,
                claims,
                now.AddMilliseconds(-30),
                now.AddDays(31),
                new SigningCredentials(rsaSecurityKey, SecurityAlgorithms.RsaSha256)
                        );

            return(handler.WriteToken(token));
        }
Esempio n. 2
0
        public ActionResult <User> Update([FromRoute] string userName,
                                          [FromBody, Required] CliendId client)
        {
            if (client == null)
            {
                return(BadRequest("Missing clientId"));
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var token = _tokenGenerator.Generate(userName, client);
                var user  = new User
                {
                    Name         = userName,
                    ConnectionId = client.ConnectionId,
                    Token        = token
                };

                _userService.Register(user);

                return(Ok(user));
            }
            catch (InvalidOperationException)
            {
                return(Problem("No username available"));
            }
        }