-
Notifications
You must be signed in to change notification settings - Fork 89
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
cb9528e
commit 980f00d
Showing
14 changed files
with
440 additions
and
136 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
132 changes: 132 additions & 0 deletions
132
src/NLog.Targets.ElasticSearch/ElasticsearchTokenProvider.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
using Newtonsoft.Json; | ||
using NLog.Common; | ||
using System; | ||
using System.Net.Http; | ||
using System.Net.Http.Headers; | ||
using System.Text; | ||
|
||
namespace NLog.Targets.ElasticSearch | ||
{ | ||
public sealed class ElasticsearchTokenProvider : IElasticsearchTokenProvider | ||
{ | ||
private const string DefaultContentType = "application/json"; | ||
private readonly Uri _baseAddress; | ||
private readonly string _username; | ||
private readonly string _password; | ||
|
||
public ElasticsearchTokenProvider(Uri baseAddress, string username, string password) | ||
{ | ||
_baseAddress = baseAddress; | ||
_password = password; | ||
_username = username; | ||
} | ||
|
||
public OAuthAccessToken GetToken() | ||
{ | ||
var tokenRequest = new | ||
{ | ||
grant_type = "password", | ||
username = _username, | ||
password = _password, | ||
}; | ||
|
||
using var stringContent = new StringContent( | ||
JsonConvert.SerializeObject(tokenRequest), | ||
Encoding.UTF8, | ||
DefaultContentType); | ||
|
||
OAuthAccessToken token = null; | ||
try | ||
{ | ||
token = DoRequest<OAuthAccessToken>(stringContent, HttpMethod.Post); | ||
if (token != null) | ||
{ | ||
token.GeneratedTime = DateTime.UtcNow.Ticks; | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
InternalLogger.Error(ex, "ElasticSearch: Error generating the token."); | ||
} | ||
|
||
return token; | ||
} | ||
|
||
public OAuthAccessToken RefreshToken(OAuthAccessToken currentToken) | ||
{ | ||
var refreshToken = new | ||
{ | ||
grant_type = "refresh_token", | ||
refresh_token = currentToken?.RefreshToken, | ||
}; | ||
|
||
using var stringContent = new StringContent( | ||
JsonConvert.SerializeObject(refreshToken), | ||
Encoding.UTF8, | ||
DefaultContentType); | ||
|
||
OAuthAccessToken token; | ||
try | ||
{ | ||
token = DoRequest<OAuthAccessToken>(stringContent, HttpMethod.Post, currentToken?.AccessToken); | ||
if (token != null) | ||
{ | ||
token.GeneratedTime = DateTime.UtcNow.Ticks; | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
InternalLogger.Error(ex, "ElasticSearch: Error refreshing the token. Trying to generate new token."); | ||
|
||
token = GetToken(); | ||
} | ||
|
||
return token; | ||
} | ||
|
||
private T DoRequest<T>(HttpContent content, HttpMethod httpMethod, string bearerToken = null) | ||
{ | ||
using var httpClient = new HttpClient { BaseAddress = _baseAddress }; | ||
httpClient.DefaultRequestHeaders.Accept.ParseAdd(DefaultContentType); | ||
using var request = new HttpRequestMessage | ||
{ | ||
Method = httpMethod, | ||
RequestUri = new Uri($"/_security/oauth2/token", UriKind.Relative), | ||
Content = content, | ||
}; | ||
|
||
if (!string.IsNullOrWhiteSpace(bearerToken)) | ||
{ | ||
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); | ||
} | ||
else | ||
{ | ||
if (!string.IsNullOrWhiteSpace(_username)) | ||
{ | ||
var encodedCredential = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{_username}:{_password}")); | ||
|
||
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", encodedCredential); | ||
} | ||
else | ||
{ | ||
InternalLogger.Error("ElasticSearch: For token generation a username must be configured."); | ||
return default; | ||
} | ||
} | ||
|
||
using var response = httpClient.SendAsync(request).GetAwaiter().GetResult(); | ||
|
||
if (!response.IsSuccessStatusCode) | ||
{ | ||
var responseContent = response.Content.ReadAsStringAsync(); | ||
|
||
InternalLogger.Error($"ElasticSearch: error trying to refresh token. Call status: {response.StatusCode}. Response: {responseContent}"); | ||
return default; | ||
} | ||
|
||
var token = JsonConvert.DeserializeObject<T>(response.Content.ReadAsStringAsync().GetAwaiter().GetResult()); | ||
|
||
return token; | ||
} | ||
} | ||
} |
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 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 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 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 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
9 changes: 9 additions & 0 deletions
9
src/NLog.Targets.ElasticSearch/IElasticsearchTokenProvider.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
namespace NLog.Targets.ElasticSearch | ||
{ | ||
public interface IElasticsearchTokenProvider | ||
{ | ||
OAuthAccessToken GetToken(); | ||
|
||
OAuthAccessToken RefreshToken(OAuthAccessToken currentToken); | ||
} | ||
} |
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 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 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using Newtonsoft.Json; | ||
|
||
namespace NLog.Targets.ElasticSearch | ||
{ | ||
public class OAuthAccessToken | ||
{ | ||
[JsonProperty(PropertyName = "access_token")] | ||
public string AccessToken { get; set; } | ||
|
||
[JsonProperty(PropertyName = "expires_in")] | ||
public long ExpiresIn { get; set; } | ||
|
||
public string Scope { get; set; } | ||
|
||
public string Type { get; set; } | ||
|
||
[JsonProperty(PropertyName = "refresh_token")] | ||
public string RefreshToken { get; set; } | ||
|
||
public long GeneratedTime { get; set; } | ||
|
||
public override int GetHashCode() | ||
{ | ||
unchecked | ||
{ | ||
var hash = 17; | ||
hash = (hash * 23) + AccessToken?.GetHashCode() ?? 0; | ||
hash = (hash * 23) + RefreshToken?.GetHashCode() ?? 0; | ||
return hash; | ||
} | ||
} | ||
|
||
public override bool Equals(object obj) | ||
{ | ||
if (obj is null) | ||
{ | ||
return false; | ||
} | ||
|
||
if (ReferenceEquals(this, obj)) | ||
{ | ||
return true; | ||
} | ||
|
||
if (obj.GetType() != GetType()) | ||
{ | ||
return false; | ||
} | ||
|
||
var objTyped = (OAuthAccessToken)obj; | ||
return this.AccessToken.Equals(objTyped.AccessToken) && this.RefreshToken.Equals(objTyped.RefreshToken); | ||
} | ||
} | ||
} |
Oops, something went wrong.