当前位置:网站首页>AspNet.WebApi.Owin custom Token request parameters
AspNet.WebApi.Owin custom Token request parameters
2022-08-01 05:20:00 【The other side of the ocean】
Asp.NET WebAPIThere are many authorization verifications in :
例如选用Bearer Token验证:利用Asp.Net Owin实现:基本套路为:(宿主Winform程序为例)
1:nuget owin相关的安装包:
Microsoft.AspNet.WebApi.OwinSelfHost
Microsoft.Owin.Security.OAuth
Microsoft.AspNet.WebApi.Owin
Other related dependencies are automatically downloaded;
2:开启webapi服务:
Microsoft.Owin.Hosting.WebApp.Start<Startup>("http://127.0.0.1:8996/");
Startup类如下:
public class Startup
{
public void Configuration(IAppBuilder app)
{
SimpleAuthorizationProvider provider = new SimpleAuthorizationProvider();
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/auth/signin"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = provider,
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions);
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}"
);
app.UseWebApi(config);
}
}
SimpleAuthorizationProvider .cs
/// <summary>
/// Token验证
/// </summary>
public class SimpleAuthorizationProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
await Task.Factory.StartNew(() => context.Validated());
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));
string userName = context.UserName;
string pwd = context.Password;
if (userName == "test" && pwd == "1")
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "User and password authentication failed!");
}
}
}
3:Postman验证:
其中:grant_type 和 username、password为固定的参数,且grant_type固定为"password",否则请求token不成功;
至于为何是这样,参考OwinFramework source code analysis can know the reason:
源码地址:https://github.com/aspnet/AspNetKatana
源码位置:TokenEndpointRequest.cs at the constructor
重点来了,If you wish to change the fetchToken的参数,该如何处理呢?
解决办法如下:
步骤1:Find the two files below the source code as shown in the figure below:Copied as is:
步骤2:Paste the above two files into the project,重命名:如:MyOAuthAuthorizationServerHandler和
MyOAuthAuthorizationServerMiddleware
步骤3:修改Setup 中的Configuration方法:
public void Configuration(IAppBuilder app)
{
SimpleAuthorizationProvider provider = new SimpleAuthorizationProvider();
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/auth/signin"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = provider,
};
//app.UseOAuthAuthorizationServer(OAuthServerOptions);
//app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions() { });
app.Use(typeof(MyOAuthAuthorizationServerMiddleware), app, OAuthServerOptions);
app.UseOAuthBearerTokens(OAuthServerOptions);
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}"
);
app.UseWebApi(config);
}
步骤4:修改 MyOAuthAuthorizationServerMiddleware 下获取HttpRequest中 Body参数的代码:
如下所示:
private async Task InvokeTokenEndpointAsync()
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
// remove milliseconds in case they don't round-trip
currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond));
IDictionary<string, string[]> formDic = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
formDic.Add(Constants.Parameters.GrantType, new string[] { "password" });
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4 * 1024, leaveOpen: true))
{
string text = await reader.ReadToEndAsync();
var userInfo= JsonConvert.DeserializeObject<UserInfo>(text);
formDic.Add(Constants.Parameters.Username, new string[] { userInfo.User });
formDic.Add(Constants.Parameters.Password, new string[] { userInfo.Pwd });
}
IFormCollection form=new FormCollection(formDic);
//Below is the original code
//IFormCollection form = await Request.ReadFormAsync();
var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form);
await Options.Provider.ValidateClientAuthentication(clientContext);
//....省略后面的代码
}
The key idea is to readBody Stream流,然后解析得到Json字符串,After converting to object,给IFormCollection赋值实例化.此后继续OwinThe functional flow of the framework remains unchanged;
实现效果如下图所示:
If you want to customize the returnJson格式呢,For example, it becomes the following:
同理:at the last return result,Modify it to the desired format:
private async Task InvokeTokenEndpointAsync()
{
DateTimeOffset currentUtc = Options.SystemClock.UtcNow;
// remove milliseconds in case they don't round-trip
currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond));
IDictionary<string, string[]> formDic = new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase);
formDic.Add(Constants.Parameters.GrantType, new string[] { "password" });
using (var reader = new StreamReader(Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4 * 1024, leaveOpen: true))
{
string text = await reader.ReadToEndAsync();
var userInfo= JsonConvert.DeserializeObject<UserInfo>(text);
formDic.Add(Constants.Parameters.Username, new string[] { userInfo.User });
formDic.Add(Constants.Parameters.Password, new string[] { userInfo.Pwd });
}
IFormCollection form=new FormCollection(formDic);
//Below is the original code
//IFormCollection form = await Request.ReadFormAsync();
var clientContext = new OAuthValidateClientAuthenticationContext(Context, Options, form);
await Options.Provider.ValidateClientAuthentication(clientContext);
if (!clientContext.IsValidated)
{
_logger.WriteError("clientID is not valid.");
if (!clientContext.HasError)
{
clientContext.SetError(Constants.Errors.InvalidClient);
}
await SendErrorAsJsonAsync(clientContext);
return;
}
var tokenEndpointRequest = new TokenEndpointRequest(form);
var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext);
AuthenticationTicket ticket = null;
if (tokenEndpointRequest.IsAuthorizationCodeGrantType)
{
// Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3
ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType)
{
// Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2
ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsClientCredentialsGrantType)
{
// Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4
// Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2
ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsRefreshTokenGrantType)
{
// Refreshing an Access Token
// http://tools.ietf.org/html/rfc6749#section-6
ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc);
}
else if (tokenEndpointRequest.IsCustomExtensionGrantType)
{
// Defining New Authorization Grant Types
// http://tools.ietf.org/html/rfc6749#section-8.3
ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc);
}
else
{
// Error Response http://tools.ietf.org/html/rfc6749#section-5.2
// The authorization grant type is not supported by the
// authorization server.
_logger.WriteError("grant type is not recognized");
validatingContext.SetError(Constants.Errors.UnsupportedGrantType);
}
if (ticket == null)
{
await SendErrorAsJsonAsync(validatingContext);
return;
}
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);
var tokenEndpointContext = new OAuthTokenEndpointContext(Context, Options, ticket, tokenEndpointRequest);
await Options.Provider.TokenEndpoint(tokenEndpointContext);
if (tokenEndpointContext.TokenIssued)
{
ticket = new AuthenticationTicket(tokenEndpointContext.Identity, tokenEndpointContext.Properties);
}
else
{
_logger.WriteError("Token was not issued to tokenEndpointContext");
validatingContext.SetError("invalid_grant");
await SendErrorAsJsonAsync(validatingContext);
return;
}
var accessTokenContext = new AuthenticationTokenCreateContext(Context, Options.AccessTokenFormat, ticket);
await Options.AccessTokenProvider.CreateAsync(accessTokenContext);
string accessToken = accessTokenContext.Token;
if (string.IsNullOrEmpty(accessToken))
{
accessToken = accessTokenContext.SerializeTicket();
}
DateTimeOffset? accessTokenExpiresUtc = ticket.Properties.ExpiresUtc;
var refreshTokenCreateContext = new AuthenticationTokenCreateContext(Context, Options.RefreshTokenFormat, accessTokenContext.Ticket);
await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext);
string refreshToken = refreshTokenCreateContext.Token;
var tokenEndpointResponseContext = new OAuthTokenEndpointResponseContext(Context, Options, ticket, tokenEndpointRequest, accessToken, tokenEndpointContext.AdditionalResponseParameters);
await Options.Provider.TokenEndpointResponse(tokenEndpointResponseContext);
var memory = new MemoryStream();
byte[] body;
/*
*
*public T Data { get; set; }
public bool IsError { get; set; }
public string Message { get; set; }
public int ErrorCode { get; set; }
*/
var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
using (var writer = new JsonTextWriter(new StreamWriter(memory)))
{
writer.WriteStartObject();
writer.WritePropertyName("Data");
TokenInfo tokenInfo = new TokenInfo();
tokenInfo.Token = accessToken;
tokenInfo.TokenType = "bearer";
JsonSerializer serializer = new JsonSerializer();
//var jsn = new JObject();
//jsn["Data"] = JObject.FromObject( tokenInfo);
serializer.Serialize(writer, tokenInfo);
writer.WritePropertyName("IsError");
writer.WriteValue(false);
writer.WritePropertyName("Message");
writer.WriteValue(String.Empty);
writer.WritePropertyName("ErrorCode");
writer.WriteValue(0);
if (accessTokenExpiresUtc.HasValue)
{
TimeSpan? expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
var expiresIn = (long)expiresTimeSpan.Value.TotalSeconds;
if (expiresIn > 0)
{
writer.WritePropertyName("expires_in");
writer.WriteValue(expiresIn);
}
}
if (!String.IsNullOrEmpty(refreshToken))
{
writer.WritePropertyName("refresh_token");
writer.WriteValue(refreshToken);
}
foreach (var additionalResponseParameter in tokenEndpointResponseContext.AdditionalResponseParameters)
{
writer.WritePropertyName(additionalResponseParameter.Key);
writer.WriteValue(additionalResponseParameter.Value);
}
writer.WriteEndObject();
writer.Flush();
body = memory.ToArray();
}
Response.ContentType = "application/json;charset=UTF-8";
Response.Headers.Set("Cache-Control", "no-cache");
Response.Headers.Set("Pragma", "no-cache");
Response.Headers.Set("Expires", "-1");
Response.ContentLength = body.Length;
await Response.WriteAsync(body, Request.CallCancelled);
}
参考#region Code for custom formatting section
边栏推荐
- 将CSV文件快速导入MySQL中
- Robot_Framework: keyword
- Selenium:简介
- 字符中的第一个唯一字符
- Qt Widget 项目对qml的加载实例
- LeetCode 387. 字符串中的第一个唯一字符
- [target detection] YOLOv7 theoretical introduction + practical test
- Selenium: JS operation
- (Codeforce 757)E. Bash Plays with Functions(积性函数)
- About making a progress bar for software initialization for Qt
猜你喜欢
Code Interview Guide for Programmers CD15 Generating an Array of Windowed Maximums
PAT serie b write the number 1002
MySQL-数据操作-分组查询-连接查询-子查询-分页查询-联合查询
力扣(LeetCode)212. 单词搜索 II(2022.07.31)
Swastika line-by-line parsing and realization of the Transformer, and German translation practice (a)
字符中的第一个唯一字符
程序员代码面试指南 CD15 生成窗口最大值数组
pytorch、tensorflow对比学习—功能组件(优化器、评估指标、Module管理)
(2022牛客多校四)H-Wall Builder II(思维)
What should I do if the neural network cannot be trained?
随机推荐
(2022牛客多校四)N-Particle Arts(思维)
Robot_Framework:关键字
初识shell脚本
The method of solving stored procedure table name passing through variable in mysql
Selenium:浏览器操作
Hunan institute of technology in 2022 ACM training sixth week antithesis
(2022牛客多校四)A-Task Computing (排序+动态规划)
Selenium: Introduction
牛客多校2022第四场A,H,K,N
(2022牛客多校四)D-Jobs (Easy Version)(三维前缀或)
小心你的字典和样板代码
LeetCode 231. 2 的幂
pytorch、tensorflow对比学习—功能组件(激活函数、模型层、损失函数)
(Codeforce 757)E. Bash Plays with Functions(积性函数)
USB3.0:VL817Q7-C0的LAYOUT指南(三)
MySQL-Data Operation-Group Query-Join Query-Subquery-Pagination Query-Joint Query
MySQL-Data Definition Language-DDLdatebase define language
Selenium:表单切换
Selenium:操作Cookie
文件的异步读写