예제 #1
0
        public async Task <IActionResult> PostLogin(Creds creds)
        {
            //todo: Ensure that these input values are not logged.
            var user = await SignInUser(creds.UserName, creds.Password);

            if (user == null)
            {
                return(BadRequest("Invalid credentials"));
            }
            var identity = await _repository.GetClaimsIdentity(user.UserName);

            var jwtAccessToken = await GetAccessToken(identity, user);

            var jwtRefreshToken = await GetRefreshToken(identity, user);

            // Create the JWT security tokens and encode it.
            var encodedJwtAccess  = new JwtSecurityTokenHandler().WriteToken(jwtAccessToken);
            var encodedJwtRefresh = new JwtSecurityTokenHandler().WriteToken(jwtRefreshToken);

            // Serialize and return the response
            var response = new
            {
                access_token  = encodedJwtAccess,
                refresh_token = encodedJwtRefresh,
                expires_in    = (int)_jwtOptions.ValidFor.TotalSeconds
            };
            var json = JsonConvert.SerializeObject(response, _serializerSettings);

            _repository.AddRefreshToken(encodedJwtRefresh, user, jwtRefreshToken.ValidTo, this.HttpContext.Connection.RemoteIpAddress.ToString());
            return(new OkObjectResult(json));
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var    clientId = context.Ticket.Properties.Dictionary["as:client_id"];
            string deviceId = context.OwinContext.Get <string>("as:device_id");

            if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(deviceId))
            {
                return;
            }
            var refreshTokenId       = Guid.NewGuid().ToString("n");
            var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");

            var token = new RefreshToken
            {
                Id         = HashHelper.GetHash(refreshTokenId),
                ClientId   = clientId,
                Subject    = context.Ticket.Identity.Name,
                DeviceId   = deviceId,
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
            };

            context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
            token.ProtectedTicket = context.SerializeTicket();
            var result = await _repository.AddRefreshToken(token);

            if (result)
            {
                context.SetToken(refreshTokenId);
            }
        }