Пример #1
0
        private async Task GenerateToken(HttpContext context)
        {
            var email     = context.Request.Form["email"];
            var password  = context.Request.Form["password"];
            var loginType = context.Request.Form["logintype"];
            var loginData = context.Request.Form["logindata"];

            var loginHandler = _handlers.FirstOrDefault(h => h.LoginType == loginType);
            // bad request if handler null

            var user = loginHandler.GetUser(loginData);

            //TODO:verify token, email or user data
            var dbUser = _loginService.GetOrCreate(user);

            if (dbUser == null)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid username or password.");

                return;
            }

            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[]
            {
                // Mandatory
                new Claim(JwtRegisteredClaimNames.Sub, dbUser.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, now.ToUniversalTime().ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer64),

                // My claims
                new Claim("AlegroUserName", dbUser.UserName)
            };

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

            var response = new
            {
                access_token = encodedJwt,
                expires_in   = (int)_options.Expiration.TotalSeconds
            };

            // Serialize and return the response
            context.Response.ContentType = "application/json";
            await context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }));
        }
Пример #2
0
 public void CreateUser([FromBody] User user)
 {
     _signUpService.GetOrCreate(user);
 }