{"id":17871215,"url":"https://github.com/stulzq/aspnetcore.authentication.apitoken","last_synced_at":"2025-07-11T04:34:14.932Z","repository":{"id":48909439,"uuid":"323867168","full_name":"stulzq/AspNetCore.Authentication.ApiToken","owner":"stulzq","description":"A asp.net core webapi token authentication \u0026 generator open source library.","archived":false,"fork":false,"pushed_at":"2021-07-06T01:51:17.000Z","size":637,"stargazers_count":32,"open_issues_count":0,"forks_count":7,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-13T06:03:23.108Z","etag":null,"topics":["aspnetcore","authentication","bearer-token","token"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/stulzq.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-12-23T10:06:24.000Z","updated_at":"2024-08-25T22:47:49.000Z","dependencies_parsed_at":"2022-09-23T23:31:31.914Z","dependency_job_id":null,"html_url":"https://github.com/stulzq/AspNetCore.Authentication.ApiToken","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stulzq%2FAspNetCore.Authentication.ApiToken","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stulzq%2FAspNetCore.Authentication.ApiToken/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stulzq%2FAspNetCore.Authentication.ApiToken/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/stulzq%2FAspNetCore.Authentication.ApiToken/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/stulzq","download_url":"https://codeload.github.com/stulzq/AspNetCore.Authentication.ApiToken/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244829483,"owners_count":20517306,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aspnetcore","authentication","bearer-token","token"],"created_at":"2024-10-28T10:27:37.067Z","updated_at":"2025-03-21T16:31:09.335Z","avatar_url":"https://github.com/stulzq.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AspNetCore.Authentication.ApiToken\n\nEnglish | [中文](README_zh-CN.md)\n\n[![Latest version](https://img.shields.io/nuget/v/AspNetCore.Authentication.ApiToken.svg)](https://www.nuget.org/packages/AspNetCore.Authentication.ApiToken/) \n\nAspNetCore.Authentication.ApiToken is an authentication component for ASP.NET Core, following the design specification of ASP.NET Core authentication framework. It is mainly used in the WebApi project to provide **issuance** and **verification** Token capabilities. The Token issued by this component is not a Json Web Token (JWT), which is similar to the Reference Token in IdentityServer4 and needs to be queried on the server to verify the validity. If there is a need for Reference Token in IdentityServer4 in your project, then IdentityServer4 is recommended for medium and large projects. If it is a small and medium-sized project, then you can consider AspNetCore.Authentication.ApiToken, which is more portable than IdentityServer4. Maintenance costs are lower. The advantage of this Token over JWT is that it can completely control the life cycle of the Token. The disadvantage is that to verify the Token, you need to query the storage every time to compare and verify (the performance can be improved by caching).\n\n## Features\n\n- Simple access, only need to implement two interfaces\n- Integrated issuance, refresh, cancellation and verification of Token\n- Support caching, Redis is implemented by default, and other caches can be easily extended\n- Support regular cleaning of expired Token background tasks\n- Support to update the user claim (role) to take effect immediately without logging in again\n- Only one Token can be valid for the same user at the same time (if a new Token is issued, all old Tokens will become invalid)\n- Support smooth transition when refreshing Token, old Token will not be invalid immediately\n- Support authentication events\n\n\n## Quick start\n\n### 1.Install\n\nInstall via Nuget in your WebApi project\n\n````shell\ndotnet add package AspNetCore.Authentication.ApiToken\n````\n\n### 2.Implementation interface IApiTokenProfileService\n\nThe main function of this interface is to query the user's Claims according to the user Id when **creating** and **refreshing** Tokens, such as commonly used: Name, Id, and Role.\n\nThe Claims provided here can be accessed in the `HttpContext.User.Claims` property after **authentication is successful**. Role Claim can be used on `[Authorize]`, such as `[Authorize(Roles = \"Admin\")]`\n\nExample（Entity Framework core）：\n\nMyApiTokenProfileService.cs\n\n````csharp\npublic class MyApiTokenProfileService : IApiTokenProfileService\n{\n    private readonly EfDbContext _dbContext;\n\n    public MyApiTokenProfileService(EfDbContext dbContext)\n    {\n        _dbContext = dbContext;\n    }\n    public async Task\u003cList\u003cClaim\u003e\u003e GetUserClaimsAsync(string userId)\n    {\n        var user = await _dbContext.Users.FirstAsync(a =\u003e a.Id == userId);\n        return new List\u003cClaim\u003e()\n        {\n            new Claim(ApiTokenClaimTypes.Subject,userId),\n            new Claim(ApiTokenClaimTypes.Name,user.Name),\n            new Claim(ApiTokenClaimTypes.Role,user.Role),\n        };\n    }\n}\n````\n\n### 3.Implementation interface IApiTokenStore\n\nThis interface is used to store, query, and delete tokens. Because the Token provided by this component needs to be checked and compared for validity verification.\n\nThe example uses the database as a storage implementation (Entity Framework core):\n\nMqApiTokenStore.cs\n````csharp\npublic class MqApiTokenStore : IApiTokenStore\n{\n    //Store token\n    public async Task StoreAsync(TokenModel token)\n    {\n        //...\n    }\n\n    //Store Token list\n    public async Task StoreAsync(List\u003cTokenModel\u003e token)\n    {\n        //...\n    }\n\n    //Get token\n    public async Task\u003cTokenModel\u003e GetAsync(string token, string scheme)\n    {\n        //...\n    }\n\n    //Get the token list\n    public async Task\u003cList\u003cTokenModel\u003e\u003e GetListAsync(string userId, string scheme)\n    {\n        //...\n    }\n\n    //Get a list of tokens of the specified type\n    public async Task\u003cList\u003cTokenModel\u003e\u003e GetListAsync(string userId, string scheme, TokenType type)\n    {\n        //...\n    }\n\n    //Update token\n    public async Task UpdateAsync(TokenModel token)\n    {\n        //...\n    }\n\n    //Update token list\n    public async Task UpdateListAsync(List\u003cTokenModel\u003e token)\n    {\n        //...\n    }\n\n    //Delete token\n    public async Task RemoveAsync(string token, string scheme)\n    {\n        //...\n    }\n\n    //Delete list\n    public async Task RemoveListAsync(string userId, string scheme)\n    {\n        //...\n    }\n\n    //Delete the Token list of the specified type\n    public async Task RemoveListAsync(string userId, string scheme, TokenType type)\n    {\n        //...\n    }\n\n    //Remove expiration token\n    public async Task\u003cint\u003e RemoveExpirationAsync()\n    {\n        //...\n    }\n}\n````\n\n### 4.Configuration\n\nStartup.cs\n\n````csharp\npublic void ConfigureServices(IServiceCollection services)\n{\n    services.AddAuthentication(ApiTokenDefaults.AuthenticationScheme)\n        .AddApiToken()\n        .AddProfileService\u003cMyApiTokenProfileService\u003e()\n        .AddTokenStore\u003cMyApiTokenStore\u003e();\n    //Other services...\n}\n````\n\n### 5.Issue token\n\nYou need to write an API for issuing tokens yourself.\n\nInject `IApiTokenOperator tokenOperator`\n\n````csharp\nvar createResult = await tokenOperator.CreateAsync(\"\u003cuserId\u003e\");\n````\n\nThe returned result contains Bearer Token and Refresh Token. Bearer Token is used for interface verification, and Refresh Token is used for Token refresh.\n\n### 6.Use Token\n\nSimilar to the way of using JWT, add Header to the request\n\n````\nAuthorization: Bearer \u003ctoken\u003e\n````\n\n### 7.Demo\n\n**Please refer to the complete implementation [SampleApp](./sample/AspNetCore.ApiToken.SampleApp/README.md)**\n\n![](assets/op.gif)\n\n## Advance\n\n### 1.Use cache\n\nInstall Nuget package：`AspNetCore.Authentication.ApiToken.Redis`\n\nAdd service on Startup.ConfigureServices `AddRedisCache(op =\u003e op.ConnectionString = \"\u003credis connection string\u003e\")`\n\nExample：\n\n```csharp\nservices.AddAuthentication(ApiTokenDefaults.AuthenticationScheme)\n    .AddApiToken(op =\u003e op.UseCache = false)\n    .AddRedisCache(op =\u003e op.ConnectionString = \"127.0.0.1:6379\")\n    .AddProfileService\u003cMyApiTokenProfileService\u003e()\n    .AddTokenStore\u003cMyApiTokenStore\u003e();\n```\n\nThe cache validity period can be customized, generally the cache validity period is the same as the token expiration time.\n\n### 2.Custom cache\n\nTo implement the `IApiTokenCacheService` interface, please refer to the implementation of [Redis](src/AspNetCore.AuthenticationApiToken.Redis/RedisTokenCacheService.cs).\n\n### 3.Clean Token Background Service\n\nPeriodic cleaning service refers to running to clean up expired tokens in the database at regular intervals, adding `AddCleanService()` to the registration service\n\nExample:\n\n````csharp\nservices.AddAuthentication(ApiTokenDefaults.AuthenticationScheme)\n    .AddApiToken(op =\u003e op.UseCache = false)\n    .AddProfileService\u003cMyApiTokenProfileService\u003e()\n    .AddTokenStore\u003cMyApiTokenStore\u003e()\n    .AddCleanService();\n````\n\nCan customize the interval time.\n\n### 4.Refresh Token\n\nInject `IApiTokenOperator` and call the `RefreshAsync(string refreshToken, string scheme)` method, it will automatically refresh and return the result.\n\nThe `ApiTokenOptions.KeepTokenValidTimeSpanOnRefresh` property can be used to set how long the old Token can be valid after refreshing.\n\n### 5.Update claim\n\nInject `IApiTokenOperator` and call `RefreshClaimsAsync(string token, string scheme)` method. Mainly used for users to update information, such as name or role, if you do not need to login again, it will take effect immediately, you can call this method.\n\n### 6.Revoke token\n\nInject `IApiTokenOperator` and call `RemoveAsync(string token, string scheme)` method.\n\n### Tips\n\nThe scheme in the above method can not be passed, but it needs to be passed in when multiple ApiToken authentication services are registered, or the ApiToken authentication is not the default scheme. This is because of the design of the authentication framework of ASP.NET Core. If you need to know the details, you can see the official documentation of ASP.NET Core.\n\n## Thanks\n\nThe following items are referred to in the design and compilation of this project：\n\n- [aspnetcore-authentication-apikey](https://github.com/mihirdilip/aspnetcore-authentication-apikey)\n- [Microsoft.AspNetCore.Authentication.JwtBearer](https://github.com/dotnet/aspnetcore/tree/master/src/Security/Authentication/JwtBearer/src) \n- [IdentityServer4](https://github.com/identityserver/identityserver4)\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstulzq%2Faspnetcore.authentication.apitoken","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstulzq%2Faspnetcore.authentication.apitoken","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstulzq%2Faspnetcore.authentication.apitoken/lists"}