コード例 #1
0
        public async Task <IActionResult> Put(ApiTokenDto dto)
        {
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound("The specified user could not be found."));
            }

            if (dto == null)
            {
                return(BadRequest());
            }
            var token = await _context.ApiTokens.SingleOrDefaultAsync(t => t.UserId == user.Id && t.Id == dto.Id);

            if (token == null)
            {
                return(NotFound());
            }

            token.Expiry = dto.Expiry;
            token.Notes  = dto.Notes;
            await _context.SaveChangesAsync();

            return(new OkResult());
        }
コード例 #2
0
        /// <summary>
        ///     Generate API autentication token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public ApiTokenDto GenerateApiToken(User user)
        {
            Trace.WriteLine("[SecurityHelper] Generating API token.");
            var identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString(CultureInfo.InvariantCulture)));

            var tokenExpiration = TimeSpan.FromDays(365);
            var props = new AuthenticationProperties
            {
                IssuedUtc = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration),
            };

            var ticket = new AuthenticationTicket(identity, props);
            var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            if (ticket.Properties.IssuedUtc == null || ticket.Properties.ExpiresUtc == null) return null;

            var tokenResponse = new ApiTokenDto
            {
                User = _mappingEngine.Map<User, UserDto>(user),
                AccessToken = token,
                TokenType = "bearer",
                ExpiresIn = tokenExpiration.TotalSeconds.ToString(CultureInfo.InvariantCulture),
                Issued = GetUtcDateTime(ticket.Properties.IssuedUtc.Value).ToString("s"),
                Expires = GetUtcDateTime(ticket.Properties.ExpiresUtc.Value).ToString("s")
            };

            return tokenResponse;
        }