-
Notifications
You must be signed in to change notification settings - Fork 307
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AspNetCore OAuth sample #61
Open
jaredpar
wants to merge
1
commit into
microsoft:master
Choose a base branch
from
jaredpar:oauth
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This provides an OAuth sample implementation for Asp.Net Core. This is my first attempt at writing my own OAuth provider for Asp.Net Core and I'm also fairly new to OAuth in general. So please let me know if there is anything that can be improved in this sample closes microsoft#45
I tried the same on a Blazor Server application and it works pretty well. It would be usefull to have sample API calls with the obtained access_token |
It would be great if you add an example API call with access_token, and code to renew the access_token using refresh_token. |
In case this is useful: this is how one can renew access_token using refresh_token, if access_token is expired: public void ConfigureServices(IServiceCollection services)
{
<snip>
AddCookie(options =>
{
options.LoginPath = "/signin";
options.LogoutPath = "/signout";
options.Events = new CookieAuthenticationEvents
{
OnValidatePrincipal = async x =>
{
await AdoOAuthUtils.OnValidatePrincipal(x, Configuration);
}
};
});
} public static async Task OnValidatePrincipal(CookieValidatePrincipalContext context, IConfiguration configuration)
{
if (context.Principal.Identity.IsAuthenticated)
{
var tokens = context.Properties.GetTokens();
var refreshToken = tokens.FirstOrDefault(t => t.Name == "refresh_token");
var accessToken = tokens.FirstOrDefault(t => t.Name == "access_token");
var expiresAt = tokens.FirstOrDefault(t => t.Name == "expires_at");
var expireTime = DateTime.Parse(expiresAt.Value);
var nowPlus5min = DateTime.Now + TimeSpan.FromMinutes(5);
// If this token expires in next 5 mins, renew it.
if (expireTime < nowPlus5min)
{
var tokenModel = await RefreshToken(refreshToken.Value, configuration);
if (tokenModel.IsError)
{
context.RejectPrincipal();
return;
}
refreshToken.Value = tokenModel.RefreshToken;
accessToken.Value = tokenModel.AccessToken;
var newExpires = DateTime.UtcNow + TimeSpan.FromSeconds(tokenModel.ExpiresIn);
expiresAt.Value = newExpires.ToString("o", CultureInfo.InvariantCulture);
context.Properties.StoreTokens(tokens);
context.ShouldRenew = true;
}
}
}
private static async Task<TokenModel> RefreshToken(string refreshToken, IConfiguration configuration)
{
TokenModel tokenModel = new TokenModel();
if (!String.IsNullOrEmpty(refreshToken))
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, AdoAuthenticationDefaults.TokenEndPoint);
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Dictionary<String, String> form = new Dictionary<String, String>()
{
{ "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" },
{ "client_assertion", configuration["AzureClientSecret"] },
{ "grant_type", "refresh_token" },
{ "assertion", refreshToken },
{ "redirect_uri", "https://localhost:44352" + AdoAuthenticationDefaults.CallbackPath }
};
requestMessage.Content = new FormUrlEncodedContent(form);
// Make the request to exchange the auth code for an access token (and refresh token)
HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
if (responseMessage.IsSuccessStatusCode)
{
// Handle successful request
String body = await responseMessage.Content.ReadAsStringAsync();
tokenModel = JObject.Parse(body).ToObject<TokenModel>();
}
else
{
tokenModel.IsError = true;
tokenModel.ErrorMessage = responseMessage.ReasonPhrase;
}
}
else
{
tokenModel.IsError = true;
tokenModel.ErrorMessage = "Invalid refresh_token";
}
return tokenModel;
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This provides an OAuth sample implementation for Asp.Net Core.
This is my first attempt at writing my own OAuth provider for Asp.Net
Core and I'm also fairly new to OAuth in general. So please let me know
if there is anything that can be improved in this sample
closes #45