-
Notifications
You must be signed in to change notification settings - Fork 28
Add method to use Auth0 authentication #21
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
Open
micheletolve
wants to merge
10
commits into
marcominerva:develop
Choose a base branch
from
micheletolve:feature/issue-14
base: develop
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
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
4fecc53
Add method to use Auth0 authentication
micheletolve e9b49ea
Update appsettings.json
micheletolve 63939b4
Remove Newtosoft.Json and renamed class
micheletolve 6cc1347
Merge branch 'feature/issue-14' of github.com:micheletolve/SimpleAuth…
micheletolve 42b8563
Fixed the default scheme name
micheletolve 98fe28a
Add return description.
micheletolve b69215e
Fixed code.
micheletolve febb47a
Return LginResponse on auth0 login request
micheletolve 1b109d0
Update file
micheletolve 980d001
Merge branch 'develop' into feature/issue-14
micheletolve File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 file contains hidden or 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 file contains hidden or 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 file contains hidden or 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 file contains hidden or 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 file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
using System.IdentityModel.Tokens.Jwt; | ||
using System.Net.Http.Headers; | ||
using System.Security.Claims; | ||
using System.Text; | ||
using System.Text.Json; | ||
using System.Text.Json.Serialization; | ||
using Microsoft.Extensions.Options; | ||
using Microsoft.IdentityModel.Protocols; | ||
using Microsoft.IdentityModel.Protocols.OpenIdConnect; | ||
using Microsoft.IdentityModel.Tokens; | ||
|
||
|
||
namespace SimpleAuthentication.Auth0; | ||
|
||
/// <summary> | ||
/// The auth0 service. | ||
/// </summary> | ||
internal class Auth0Service : IAuth0Service | ||
{ | ||
private readonly Auth0Settings auth0Setting; | ||
private readonly IHttpClientFactory httpClientFactory; | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="Auth0Service"/> class. | ||
/// </summary> | ||
/// <param name="auth0SettingOptions">The auth0 setting options.</param> | ||
/// <param name="httpClientFactory">The http client factory.</param> | ||
public Auth0Service(IOptions<Auth0Settings> auth0SettingOptions, IHttpClientFactory httpClientFactory) | ||
{ | ||
auth0Setting = auth0SettingOptions.Value; | ||
this.httpClientFactory = httpClientFactory; | ||
} | ||
|
||
/// <summary> | ||
/// Obtains the token async. | ||
/// </summary> | ||
/// <param name="claims">The claims.</param> | ||
/// <returns>A Task.</returns> | ||
public async Task<string> ObtainTokenAsync(IList<Claim>? claims = null) | ||
{ | ||
claims ??= new List<Claim>(); | ||
|
||
var jsonObject = new | ||
{ | ||
client_id = auth0Setting.ClientId, | ||
client_secret = auth0Setting.ClientSecret, | ||
audience = auth0Setting.Audience, | ||
grant_type = auth0Setting.GrantType | ||
}; | ||
|
||
string json = JsonSerializer.Serialize(value: jsonObject); | ||
PrepareHttpClient(json, out HttpClient client, out StringContent content); | ||
|
||
try | ||
{ | ||
HttpResponseMessage httpResponseMessage = await client.PostAsync("/oauth/token", content); | ||
|
||
if (httpResponseMessage.IsSuccessStatusCode) | ||
{ | ||
var response = httpResponseMessage.Content.ReadAsStringAsync(); | ||
var token = JsonSerializer.Deserialize<Auth0TokenResponse>(response.Result)!; | ||
|
||
claims.Update(ClaimTypes.Expiration, token.ExpiresIn.ToString()); | ||
claims.Update(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString()); | ||
|
||
return token.Token; | ||
} | ||
|
||
return httpResponseMessage.ReasonPhrase!; | ||
} | ||
catch (HttpRequestException e) | ||
{ | ||
throw new HttpRequestException($"Error occurred while sending the request to obtain the Jwt Token from Auth0 provider. Error {e.Message}"); | ||
//return e.Message; | ||
} | ||
} | ||
|
||
#region PrivateMethod | ||
/// <summary> | ||
/// Prepares the http client. | ||
/// </summary> | ||
/// <param name="json">The json.</param> | ||
/// <param name="client">The client.</param> | ||
/// <param name="content">The content.</param> | ||
private void PrepareHttpClient(string json, out HttpClient client, out StringContent content) | ||
{ | ||
var baseUri = new Uri($"https:/{auth0Setting.Domain}"); | ||
content = SetContent(json); | ||
|
||
client = httpClientFactory.CreateClient(auth0Setting.SchemeName); | ||
client.Timeout = TimeSpan.FromSeconds(30); | ||
client.BaseAddress = baseUri; | ||
client.DefaultRequestHeaders.Host = baseUri.Host; | ||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); | ||
} | ||
|
||
/// <summary> | ||
/// Configure the content for an http request | ||
/// </summary> | ||
/// <param name="json">The json serialized of the body</param> | ||
/// <returns>the content readey for the request</returns> | ||
private static StringContent SetContent(string json) | ||
{ | ||
if (string.IsNullOrEmpty(json)) | ||
return null; | ||
|
||
StringContent content = new(json, Encoding.UTF8, "application/json"); | ||
content.Headers.ContentLength = json.Length; | ||
return content; | ||
} | ||
#endregion | ||
} | ||
|
||
/// <summary> | ||
/// The Auth0TokenResponse class. | ||
/// </summary> | ||
public record class Auth0TokenResponse | ||
{ | ||
/// <summary> | ||
/// Gets or sets the token. | ||
/// </summary> | ||
[JsonPropertyName("access_token")] | ||
public string Token { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the expires in. | ||
/// </summary> | ||
[JsonPropertyName("expires_in")] | ||
public int ExpiresIn { get; set; } | ||
|
||
/// <summary> | ||
/// Gets or sets the type. | ||
/// </summary> | ||
[JsonPropertyName("token_type")] | ||
public string Type { get; set; } | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="Auth0TokenResponse"/> class. | ||
/// </summary> | ||
/// <param name="token">The token.</param> | ||
/// <param name="expiresIn">The expires in.</param> | ||
/// <param name="type">The type.</param> | ||
public Auth0TokenResponse(string token, int expiresIn, string type) | ||
{ | ||
this.Token = token; | ||
this.ExpiresIn = expiresIn; | ||
this.Type = type; | ||
} | ||
} |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
using Microsoft.AspNetCore.Authentication.JwtBearer; | ||
|
||
namespace SimpleAuthentication.Auth0 | ||
{ | ||
/// <summary> | ||
/// Options class provides information needed to control Auth0 Authentication handler behavior. | ||
/// </summary> | ||
public class Auth0Settings | ||
{ | ||
/// <summary> | ||
/// Gets or sets The authentication scheme name (Default: Bearer). | ||
/// </summary> | ||
public string SchemeName { get; set; } = JwtBearerDefaults.AuthenticationScheme; | ||
|
||
/// <summary> | ||
/// Gets or sets the cryptographic algorithm that is used to generate the digital signature (Default: RS256). | ||
/// </summary> | ||
public string Algorithm { get; set; } = "RS256"; | ||
|
||
/// <summary> | ||
/// Gets or sets the domain. | ||
/// </summary> | ||
public string Domain { get; set; } = null!; | ||
|
||
/// <summary> | ||
/// Gets or sets the valid audiences that will be used to check against the token's audience. | ||
/// </summary> | ||
public string Audience { get; set; } = null!; | ||
|
||
/// <summary> | ||
/// Gets or sets the client id. | ||
/// </summary> | ||
public string ClientId { get; set; } = null!; | ||
|
||
/// <summary> | ||
/// Gets or sets the client secret. | ||
/// </summary> | ||
public string ClientSecret { get; set; } = null!; | ||
|
||
/// <summary> | ||
/// Gets or sets the grant type. | ||
/// </summary> | ||
public string GrantType { get; set; } = "client_credentials"; | ||
} | ||
} |
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
using System.Security.Claims; | ||
|
||
namespace SimpleAuthentication.Auth0 | ||
{ | ||
/// <summary> | ||
/// Provides methods for Auth0 Bearer generation and validation. | ||
/// </summary> | ||
public interface IAuth0Service | ||
{ | ||
/// <summary> | ||
/// Obtains a bearer token string from Auth0 provider. | ||
/// </summary> | ||
/// <param name="claims">The claims list.</param> | ||
/// <returns>The JWT bearer token.</returns> | ||
Task<string> ObtainTokenAsync(IList<Claim>? claims = null); | ||
} | ||
} |
This file contains hidden or 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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.