コード例 #1
0
        private async Task <string> GenerateAccessTokenAsync()
        {
            var guid = Guid.NewGuid().ToString();
            await _accessTokenRepository.AddAsync(guid);

            return(guid);
        }
コード例 #2
0
        public async Task <string> CreateTokenAsync(long githubRepositoryId)
        {
            Repository repository = await _gitHubUserModelService.GetRepositoryAsync(githubRepositoryId);

            if (repository == null)
            {
                throw new ArgumentException("Repository does not exist or no permission to access given repository.");
            }

            var accessTokens = await _tokenRepository.GetByRepositoryIdsAsync(new[] { githubRepositoryId });

            if (accessTokens.Any())
            {
                throw new ArgumentException("Repository already has a token.");
            }

            var tokenHandler       = new JsonWebTokenHandler();
            var signingCredentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256Signature);

            var user = _contextAccessor.HttpContext.User;

            var accessToken = new AccessToken()
            {
                Id = Guid.NewGuid(),
                GitHubRepositoryId = repository.Id,
                IssuedAt           = DateTimeOffset.UtcNow,
                IssuedTo           = user.Claims.First(c => c.Type.Equals(ClaimTypes.NameIdentifier)).Value
            };

            await _tokenRepository.AddAsync(accessToken);

            var payload = new JObject()
            {
                { JwtRegisteredClaimNames.Aud, "MSBLOC.Api" },
                { JwtRegisteredClaimNames.Jti, accessToken.Id },
                { JwtRegisteredClaimNames.Iat, accessToken.IssuedAt.ToUnixTimeSeconds() },
                { "urn:msbloc:repositoryId", repository.Id },
                { "urn:msbloc:repositoryName", repository.Name },
                { "urn:msbloc:repositoryOwner", repository.Owner },
                { "urn:msbloc:repositoryOwnerId", repository.OwnerId },
                { JwtRegisteredClaimNames.Sub, accessToken.IssuedTo },
            };

            var accessTokenString = tokenHandler.CreateToken(payload, signingCredentials);

            return(accessTokenString);
        }