当前位置:网站首页>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
边栏推荐
- (more than 2022 cattle school four) A - Task Computing + dynamic programming (sort)
- pytorch、tensorflow对比学习—功能组件(优化器、评估指标、Module管理)
- Excuse me, only primary key columns can be queried using sql in table storage. Does ots sql not support non-primary keys?
- 2022年超全的Android面经(附含面试题|进阶资料)
- Use controls as brushes to get bitmap code records
- LeetCode 387. 字符串中的第一个唯一字符
- 使用string 容器翻转 字母
- 图片更新之后Glide加载依旧是原来的图片问题
- 零序电流继电器器JL-8C-12-2-2
- Selenium:元素定位
猜你喜欢
PAT乙级 1002 写出这个数
[target detection] YOLOv7 theoretical introduction + practical test
II. Binary tree to Offer 68 - recent common ancestor
MySQL-Data Operation-Group Query-Join Query-Subquery-Pagination Query-Joint Query
pytorch、tensorflow对比学习—功能组件(激活函数、模型层、损失函数)
Robot_Framework: Assertion
Selenium:操作Cookie
pytroch、tensorflow对比学习—搭建模型范式(构建模型方法、训练模型范式)
SL-12/2过流继电器
MySQL-数据定义语言-DDLdatebase define language
随机推荐
Error: AttributeError: module 'matplotlib' has no attribute 'figure'
leetcode43 字符串相乘
(2022 Nioke Duo School IV) H-Wall Builder II (Thinking)
2022年湖南工学院ACM集训第六次周测题解
LeetCode 387. 字符串中的第一个唯一字符
y83. Chapter 4 Prometheus Factory Monitoring System and Actual Combat -- Advanced Prometheus Alarm Mechanism (14)
Robot_Framework:常用内置关键字
挑战52天背完小猪佩奇(第01天)
Selenium:元素定位
WPF入门项目必知必会-初步了解数据绑定 binding
可视化全链路日志追踪
Power button (LeetCode) 212. The word search II (2022.07.31)
Use controls as brushes to get bitmap code records
将CSV文件快速导入MySQL中
pytorch、tensorflow对比学习—张量
II. Binary tree to Offer 68 - recent common ancestor
2022.7.27好题选讲
ORACLE 实现另外一个用户修改包(package)
CSP-S2019 Day1
Selenium: Popup Handling