引言
.Net Core可以很方便的集成EF和Identity;假如你的系统已经使用了Token验证,这在内部系统中很好的做认证和授权
那要是还需要单独给一个API提供外部验证呢?
比如你的接口需要提供给第三方平台,而你的系统又没做开放平台的功能本文就可参考一二.
解决方案
用户名密码配置于appsettings.json
文件中
假如有管理第三方API的功能,也可以存表里
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| [ProducesResponseType(typeof(Response<string>), 200)] [AllowAnonymous] public async Task<IActionResult> TestAsync(string parm1, int param2) {
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("用户名/密码错误"); } }
|
调用非常简单:
1 2 3 4 5 6 7 8 9
| var client = new HttpClient();
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
即可