以编程方式生成 OAuth2 令牌,在我的情况下不需要 lgoin
Generate OAuth2 token programiticly , No lgoin needed in my case
我将 OAuth2 用于 asp.net WEB API。
在我的例子中,用户将仅使用他们的 phone 号码登录,他们将收到带有验证码的短信。
用户使用验证码确认phone号的方法如下:
[AllowAnonymous]
[Route("ConfrimPhoneNumber")]
[HttpPost]
public async Task<IHttpActionResult> VerifyPhoneNumber(VerfyPhoneModel Model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Verify phone number.
//..
//..
//Get Application User
// I need to genereate and return token from here .
}
我想要的是为该用户生成访问令牌和刷新令牌。
提前感谢您的帮助。
我假设您在 Visual Studio 中使用默认的 SPA 模板。在 Startup.Auth.cs 你有一个静态 属性:
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
如果您想创建 OAuth2 令牌,您可以使用此静态引用来生成令牌:
Startup.OAuthOptions.AccessTokenFormat.Protect(authenticationTicket);
我想分享我为完成这项工作所做的一切我从其他不同的帖子中收集了答案;你可以在这个答案的末尾找到 link。
如果有人有任何意见或想法,请与我们分享。
用户注册为响应后,使用刷新令牌生成本地访问令牌。
作为Peter Hedberg回答;我们需要在启动 class 中将 OAuthOptions 设为公共和静态:
public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
然后我创建了助手 class 来生成本地访问令牌并刷新
public async Task<JObject> GenerateLocalAccessToken(ApplicationUser user)
{
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
//Create the ticket then the access token
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
ticket.Properties.IssuedUtc = DateTime.UtcNow;
ticket.Properties.ExpiresUtc = DateTime.UtcNow.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
//Create refresh token
Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
Request.GetOwinContext(),
Startup.OAuthOptions.AccessTokenFormat, ticket);
await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
properties.Dictionary.Add("refresh_token", context.Token);
//create the Token Response
JObject tokenResponse = new JObject(
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", Startup.OAuthServerOptions.AccessTokenExpireTimeSpan.TotalSeconds.ToString()),
new JProperty("refresh_token", context.Token),
new JProperty("userName", user.UserName),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
);
return tokenResponse;
}
在 SimpleRefreshTokenProvider CreateAsync 方法中使用基本 context.SerializeTicket 时出现问题。来自 Bit Of Technology
的消息
Seems in the ReceiveAsync method, the context.DeserializeTicket is not
returning an Authentication Ticket at all in the external login case.
When I look at the context.Ticket property after that call it’s null.
Comparing that to the local login flow, the DeserializeTicket method
sets the context.Ticket property to an AuthenticationTicket. So the
mystery now is how come the DeserializeTicket behaves differently in
the two flows. The protected ticket string in the database is created
in the same CreateAsync method, differing only in that I call that
method manually in the GenerateLocalAccessTokenResponse, vs. the Owin
middlware calling it normally… And neither SerializeTicket or
DeserializeTicket throw an error…
因此,您需要使用Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer 对票证进行序列化和反序列化。它看起来像这样:
Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer
= new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
token.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));
而不是:
token.ProtectedTicket = context.SerializeTicket();
对于 ReceiveAsync 方法:
Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(refreshToken.ProtectedTicket)));
而不是:
context.DeserializeTicket(refreshToken.ProtectedTicket);
我将 OAuth2 用于 asp.net WEB API。
在我的例子中,用户将仅使用他们的 phone 号码登录,他们将收到带有验证码的短信。
用户使用验证码确认phone号的方法如下:
[AllowAnonymous]
[Route("ConfrimPhoneNumber")]
[HttpPost]
public async Task<IHttpActionResult> VerifyPhoneNumber(VerfyPhoneModel Model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Verify phone number.
//..
//..
//Get Application User
// I need to genereate and return token from here .
}
我想要的是为该用户生成访问令牌和刷新令牌。
提前感谢您的帮助。
我假设您在 Visual Studio 中使用默认的 SPA 模板。在 Startup.Auth.cs 你有一个静态 属性:
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
如果您想创建 OAuth2 令牌,您可以使用此静态引用来生成令牌:
Startup.OAuthOptions.AccessTokenFormat.Protect(authenticationTicket);
我想分享我为完成这项工作所做的一切我从其他不同的帖子中收集了答案;你可以在这个答案的末尾找到 link。
如果有人有任何意见或想法,请与我们分享。
用户注册为响应后,使用刷新令牌生成本地访问令牌。
作为Peter Hedberg回答;我们需要在启动 class 中将 OAuthOptions 设为公共和静态:
public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
然后我创建了助手 class 来生成本地访问令牌并刷新
public async Task<JObject> GenerateLocalAccessToken(ApplicationUser user)
{
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
OAuthDefaults.AuthenticationType);
AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
//Create the ticket then the access token
var ticket = new AuthenticationTicket(oAuthIdentity, properties);
ticket.Properties.IssuedUtc = DateTime.UtcNow;
ticket.Properties.ExpiresUtc = DateTime.UtcNow.Add(Startup.OAuthServerOptions.AccessTokenExpireTimeSpan);
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
//Create refresh token
Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext context =
new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
Request.GetOwinContext(),
Startup.OAuthOptions.AccessTokenFormat, ticket);
await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
properties.Dictionary.Add("refresh_token", context.Token);
//create the Token Response
JObject tokenResponse = new JObject(
new JProperty("access_token", accessToken),
new JProperty("token_type", "bearer"),
new JProperty("expires_in", Startup.OAuthServerOptions.AccessTokenExpireTimeSpan.TotalSeconds.ToString()),
new JProperty("refresh_token", context.Token),
new JProperty("userName", user.UserName),
new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()),
new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString())
);
return tokenResponse;
}
在 SimpleRefreshTokenProvider CreateAsync 方法中使用基本 context.SerializeTicket 时出现问题。来自 Bit Of Technology
的消息Seems in the ReceiveAsync method, the context.DeserializeTicket is not returning an Authentication Ticket at all in the external login case. When I look at the context.Ticket property after that call it’s null. Comparing that to the local login flow, the DeserializeTicket method sets the context.Ticket property to an AuthenticationTicket. So the mystery now is how come the DeserializeTicket behaves differently in the two flows. The protected ticket string in the database is created in the same CreateAsync method, differing only in that I call that method manually in the GenerateLocalAccessTokenResponse, vs. the Owin middlware calling it normally… And neither SerializeTicket or DeserializeTicket throw an error…
因此,您需要使用Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer 对票证进行序列化和反序列化。它看起来像这样:
Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer
= new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
token.ProtectedTicket = System.Text.Encoding.Default.GetString(serializer.Serialize(context.Ticket));
而不是:
token.ProtectedTicket = context.SerializeTicket();
对于 ReceiveAsync 方法:
Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer serializer = new Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer();
context.SetTicket(serializer.Deserialize(System.Text.Encoding.Default.GetBytes(refreshToken.ProtectedTicket)));
而不是:
context.DeserializeTicket(refreshToken.ProtectedTicket);