312 字
2 分钟
.Net自定义密码验证
引言
.Net Core可以很方便的集成EF和Identity;假如你的系统已经使用了Token验证,这在内部系统中很好的做认证和授权
那要是还需要单独给一个API提供外部验证呢?
比如你的接口需要提供给第三方平台,而你的系统又没做开放平台的功能本文就可参考一二.
解决方案
用户名密码配置于appsettings.json文件中
假如有管理第三方API的功能,也可以存表里
代码如下:
[ProducesResponseType(typeof(Response<string>), 200)] [AllowAnonymous] public async Task<IActionResult> TestAsync(string parm1, int param2) { //HttpContext. //HttpContext.Request.Headers.Values
var headStr = Request.Headers["Authorization"]; if (string.IsNullOrEmpty(headStr)) { throw new Exception( "请填写用户名和密码"); } var header = AuthenticationHeaderValue.Parse(headStr); if (header == null || header.Parameter == null) throw new Exception( "请填写用户名和密码"); if (header.Scheme != "Basic") throw new Exception("仅支持基础身份验证");
Encoding encoding = Encoding.GetEncoding("iso-8859-1"); string usernamePassword = encoding.GetString(Convert.FromBase64String(header.Parameter));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex); var password = usernamePassword.Substring(seperatorIndex + 1);
if (_options.Password != password || _options.UserName != username) { throw new Exception("用户名/密码错误"); } //你的代码 }调用非常简单:
var client = new HttpClient();
//请求头部 base64加密 var bytes = Encoding.UTF8.GetBytes( $"{_option.UserName}:{_option.Password}"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes)); var msg = await client .PostAsync( _option.BaseUrl + $"/api/Test?param1={param1}¶m2={param2}", null);在Postman测试时Authorization选择 Basic Auth即可