如何在 Web 中实现 Oauth Refresh Token Api 2
How to implement Oauth Refresh Token in Web Api 2
Startup.Auth代码:
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new FirebirdAuthorizationServerProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true
};
我正在使用 FirebirdProvider、上下文并在道具中添加访问令牌,这是我函数的定义:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
......
context.Request.Context.Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
这是我获取令牌的电话:
public async Task<User> GetUserToken(string username, string password)
{
try
{
User user = new User();
if (username == null || password == null || !CrossConnectivity.Current.IsConnected)
return null;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent requestContent = new StringContent("grant_type=password&username=" + username + "&password=" + password + "&login_type=" + "sys_dash_users", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);
if (responseMessage.IsSuccessStatusCode)
{
string jsonMessage;
using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
user = (User)JsonConvert.DeserializeObject(jsonMessage, typeof(User));
return user;
}
else
{
return null;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex);
string error = ex.Message;
return null;
}
}
我不知道如何制作刷新令牌,也找不到好的教程。如何做到这一点
我回答了我自己的问题。如果有人需要这是我的代码:
添加了 SimpleRefreshTokenProvider:
public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
var guid = Guid.NewGuid().ToString();
// maybe only create a handle the first time, then re-use for same client
// copy properties and set the desired lifetime of refresh token
var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
{
IssuedUtc = context.Ticket.Properties.IssuedUtc,
ExpiresUtc = DateTime.UtcNow.AddYears(1)
};
var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
//_refreshTokens.TryAdd(guid, context.Ticket);
_refreshTokens.TryAdd(guid, refreshTokenTicket);
// consider storing only the hash of the handle
context.SetToken(guid);
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(context.Token, out ticket))
{
context.SetTicket(ticket);
}
}
public void Create(AuthenticationTokenCreateContext context)
{
throw new NotImplementedException();
}
public void Receive(AuthenticationTokenReceiveContext context)
{
throw new NotImplementedException();
}
}
并在 Startup.Authc.cs
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new FirebirdAuthorizationServerProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true,
RefreshTokenProvider = new SimpleRefreshTokenProvider(),
};
Startup.Auth代码:
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new FirebirdAuthorizationServerProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true
};
我正在使用 FirebirdProvider、上下文并在道具中添加访问令牌,这是我函数的定义:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
......
context.Request.Context.Authentication.SignIn(new AuthenticationProperties { IsPersistent = true }, identity);
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
这是我获取令牌的电话:
public async Task<User> GetUserToken(string username, string password)
{
try
{
User user = new User();
if (username == null || password == null || !CrossConnectivity.Current.IsConnected)
return null;
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent requestContent = new StringContent("grant_type=password&username=" + username + "&password=" + password + "&login_type=" + "sys_dash_users", Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);
if (responseMessage.IsSuccessStatusCode)
{
string jsonMessage;
using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
user = (User)JsonConvert.DeserializeObject(jsonMessage, typeof(User));
return user;
}
else
{
return null;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex);
string error = ex.Message;
return null;
}
}
我不知道如何制作刷新令牌,也找不到好的教程。如何做到这一点
我回答了我自己的问题。如果有人需要这是我的代码:
添加了 SimpleRefreshTokenProvider:
public class SimpleRefreshTokenProvider : IAuthenticationTokenProvider
{
private static ConcurrentDictionary<string, AuthenticationTicket> _refreshTokens = new ConcurrentDictionary<string, AuthenticationTicket>();
public async Task CreateAsync(AuthenticationTokenCreateContext context)
{
var guid = Guid.NewGuid().ToString();
// maybe only create a handle the first time, then re-use for same client
// copy properties and set the desired lifetime of refresh token
var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
{
IssuedUtc = context.Ticket.Properties.IssuedUtc,
ExpiresUtc = DateTime.UtcNow.AddYears(1)
};
var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
//_refreshTokens.TryAdd(guid, context.Ticket);
_refreshTokens.TryAdd(guid, refreshTokenTicket);
// consider storing only the hash of the handle
context.SetToken(guid);
}
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
AuthenticationTicket ticket;
if (_refreshTokens.TryRemove(context.Token, out ticket))
{
context.SetTicket(ticket);
}
}
public void Create(AuthenticationTokenCreateContext context)
{
throw new NotImplementedException();
}
public void Receive(AuthenticationTokenReceiveContext context)
{
throw new NotImplementedException();
}
}
并在 Startup.Authc.cs
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new FirebirdAuthorizationServerProvider(PublicClientId),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AllowInsecureHttp = true,
RefreshTokenProvider = new SimpleRefreshTokenProvider(),
};