GitLab.TokenRotation 1.3.0

dotnet add package GitLab.TokenRotation --version 1.3.0
                    
NuGet\Install-Package GitLab.TokenRotation -Version 1.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GitLab.TokenRotation" Version="1.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GitLab.TokenRotation" Version="1.3.0" />
                    
Directory.Packages.props
<PackageReference Include="GitLab.TokenRotation" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GitLab.TokenRotation --version 1.3.0
                    
#r "nuget: GitLab.TokenRotation, 1.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GitLab.TokenRotation@1.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GitLab.TokenRotation&version=1.3.0
                    
Install as a Cake Addin
#tool nuget:?package=GitLab.TokenRotation&version=1.3.0
                    
Install as a Cake Tool

GitLab.TokenRotation

NuGet библиотека для автоматического продления токенов GitLab через self-rotate API.

Установка

dotnet add package GitLab.TokenRotation

Быстрый старт

1. Настройка appsettings.json

{
  "TokenRotation": {
    "GitLabBaseUrl": "https://gitlab.example.com",
    "ProjectId": 123,
    "RotationInterval": "30.00:00:00",
    "ExpirationThreshold": "7.00:00:00",
    "MaxRetryAttempts": 3,
    "RetryDelay": "00:05:00",
    "EnableBackgroundService": true,
    "Tokens": [
      {
        "Name": "BotToken",
        "TokenId": 456,
        "CurrentToken": "glpat-xxxxxxxxxxxxxxxxxxxx",
        "ConfigurationPath": "appsettings.json",
        "EnableRotation": true
      },
      {
        "Name": "GraphQlToken", 
        "TokenId": 789,
        "CurrentToken": "glpat-yyyyyyyyyyyyyyyyyyyy",
        "ConfigurationPath": "appsettings.json",
        "EnableRotation": true
      }
    ]
  }
}

2. Регистрация сервисов в Program.cs

using GitLab.TokenRotation.Extensions;

var builder = WebApplication.CreateBuilder(args);

// Добавление сервисов ротации токенов с фоновым сервисом
builder.Services.AddGitLabTokenRotationWithBackgroundService(
    builder.Configuration,
    options =>
    {
        // Дополнительная настройка при необходимости
        options.RotationInterval = TimeSpan.FromDays(30);
        options.ExpirationThreshold = TimeSpan.FromDays(7);
    });

var app = builder.Build();

3. Использование сервиса

public class MyService
{
    private readonly ITokenRotationService _tokenRotationService;
    
    public MyService(ITokenRotationService tokenRotationService)
    {
        _tokenRotationService = tokenRotationService;
    }
    
    public async Task CheckAndRotateTokenAsync()
    {
        var tokenConfig = new TokenConfiguration
        {
            Name = "BotToken",
            TokenId = 456,
            CurrentToken = "glpat-xxxxxxxxxxxxxxxxxxxx",
            ConfigurationPath = "appsettings.json",
            EnableRotation = true
        };
        
        var result = await _tokenRotationService.RotateTokenIfNeededAsync(tokenConfig);
        
        if (result.Success)
        {
            Console.WriteLine($"Token rotated successfully. New token: {result.NewToken}");
        }
        else
        {
            Console.WriteLine($"Token rotation failed: {result.ErrorMessage}");
        }
    }
}

Настройки

TokenRotationSettings

  • GitLabBaseUrl - Базовый URL GitLab сервера
  • ProjectId - ID проекта в GitLab
  • RotationInterval - Интервал проверки токенов фоновым сервисом
  • ExpirationThreshold - За сколько времени до истечения начинать ротацию
  • MaxRetryAttempts - Максимальное количество попыток ротации
  • RetryDelay - Задержка между попытками
  • EnableBackgroundService - Включить фоновый сервис автоматической ротации

TokenConfiguration

  • Name - Имя токена для идентификации
  • TokenId - ID токена в GitLab
  • CurrentToken - Текущий токен
  • ConfigurationPath - Путь к файлу конфигурации для автоматического обновления
  • EnableRotation - Включить ротацию для этого токена

Расширенное использование

Кастомный конфигурационный updater

public class CustomTokenUpdater : ITokenConfigurationUpdater
{
    public async Task UpdateTokenAsync(TokenConfiguration tokenConfig, string newToken, CancellationToken cancellationToken = default)
    {
        // Кастомная логика обновления конфигурации
        // Например, обновление в базе данных или внешнем сервисе
    }
}

// Регистрация кастомного updater'а
builder.Services.AddGitLabTokenRotation(builder.Configuration)
               .AddTokenConfigurationUpdater<CustomTokenUpdater>();

Только основные сервисы без фонового процесса

builder.Services.AddGitLabTokenRotation(builder.Configuration);

API GitLab

Библиотека использует GitLab self-rotate API:

  • GET /api/v4/projects/{id}/access_tokens/{token_id} - получение информации о токене
  • POST /api/v4/projects/{id}/access_tokens/{token_id}/rotate - ротация токена

Логирование

Библиотека использует стандартный ILogger для логирования операций:

  • Информация о успешных ротациях
  • Предупреждения о проблемах
  • Ошибки при неудачных ротациях

Требования

  • .NET 6.0 или выше
  • Токены GitLab с правами на self-rotate
  • Доступ к GitLab API

Лицензия

MIT License

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.0 408 7/25/2025
1.2.0 407 7/25/2025
1.1.0 418 7/25/2025
1.0.0 432 7/24/2025