description
Rights authentication is the process of determining the identity of a user and determining whether a user has the right to access resources.
Today, I would like to share with you a token-based authentication mechanism like JWT
Based on the token-based authentication mechanism, it does not need to retain the user's authentication information or session information on the server. This means that applications based on the token authentication mechanism do not need to consider which server the user logs in, which provides convenience for application expansion.
The process goes like this:
- The user uses the username and password to request the server
- Server authenticates user information
- The server sends a token to the user through verification
- The client stores the token and attaches the token value with each request
- The server verifies the token value and returns data
Then today, I will give you a permission certificate similar to Jwt
demo
Create a new authorization filter that inherits IAuthorizationFilter
public class ApiAuthorize : IAuthorizationFilter
{}
Create a new feature that requires application authorization and a feature that allows access without authentication
public class MyAuthentication:Attribute, IFilterMetadata
{
}
public class MyNoAuthentication : Attribute, IFilterMetadata
{
}
We need to determine in our authorization filter whether the request header has the feature of application authorization and the feature of allowing access without authentication. If there is a feature that allows access without authentication, we will directly enter the next pipe. If there is an application authorization feature, then token judgment is made
public class ApiAuthorize : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (context.Filters.Contains(new MyNoAuthentication()))
{
return;
}
var authorize = context.HttpContext.Request.Headers["MyAuthentication"];
if (string.IsNullOrWhiteSpace(authorize))
{
context.Result = new JsonResult("请求authorize不能为空");
return;
}
if (!MemoryCacheHelper.Exists(authorize))
{
context.Result = new JsonResult("无效的授权信息或授权信息已过期");
return;
}
}
}
Some friends may have discovered it, so how can we access the Token? The general solution is to use Cache to process it. I won't discuss it too much here. If you want to know about it, you can read my previous article!
CacheHelper code
public class MemoryCacheHelper
{
public static MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
/// <summary>
/// 验证缓存项是否存在
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public static bool Exists(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _cache.TryGetValue(key, out _);
}
/// <summary>
/// 获取缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <returns></returns>
public static object Get(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (!Exists(key))
throw new ArgumentNullException(nameof(key));
return _cache.Get(key);
}
/// <summary>
/// 添加缓存
/// </summary>
/// <param name="key">缓存Key</param>
/// <param name="value">缓存Value</param>
/// <param name="expiresSliding">滑动过期时长(如果在过期时间内有操作,则以当前时间点延长过期时间)</param>
/// <param name="expiressAbsoulte">绝对过期时长</param>
/// <returns></returns>
public static bool AddMemoryCache(string key, object value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_cache.Set(key, value,
new MemoryCacheEntryOptions()
{
SlidingExpiration = new TimeSpan(0, 0, 10),
Priority = CacheItemPriority.NeverRemove,
AbsoluteExpiration = DateTime.Now.AddMinutes(1)
});
return Exists(key);
}
}
The authority authentication code is basically completed, let's go back to the process
The user uses the username and password to request the server, the server verifies the user's information, and the server sends a token to the user through verification
For a commercial software, most interfaces require application authorization before they can be used, so we register them globally and register them in the StartUp class.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(o=>
{
o.Filters.Add<ApiAuthorize>();
o.Filters.Add<MyAuthentication>();
});
}
I won't explain too much about the principle of token generation here. In this example, AES encryption is used to generate token, and the request token interface of our server adds a feature that allows access without authentication, and then a token is issued.
[HttpGet("GetToken")]
[MyNoAuthentication]
public IActionResult GetToken(string UserCode)
{
string token= AESEncrypt.Encrypt(UserCode);
MemoryCacheHelper.AddMemoryCache(token, User);
eturn Ok(token);
}
Use the Postman request to generate a token, as shown in the figure

Then we add an interface that requires application authorization. Since we have registered the global application authorization feature, we do not need to bring this feature.
[HttpGet("GetUserInformation")]
public IActionResult GetUserInformation()
{
return Ok(new { Name="123",Age=18,Sex="性别"});
}
Use postman to request the interface without a token, as shown in the figure

Bring a token and use postman to request the interface, as shown in the figure

Through the example just now, we have a clear understanding of the process of authority authentication, and this is the end of today's introduction!
Finally, if you like my article, please pay attention and like it, hoping that the net ecosystem will get better and better!