Skip to content

Commit d3f4da4

Browse files
committed
Added extension methods for setting the authorization header of an "IHttpRequest"
The package already contains a "SetAuthorizationHeader" extension method for setting the raw header value. To help developers in more specific cases, the package now also has the "SetAuthorizationBasic" and "SetAuthorizationBearer" extension methods.
1 parent e4a61d1 commit d3f4da4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/Skybrud.Essentials.Http/HttpRequestExtensions.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using Newtonsoft.Json;
33
using Newtonsoft.Json.Linq;
44
using Skybrud.Essentials.Http.Collections;
5+
using Skybrud.Essentials.Security;
56
using System.Diagnostics.CodeAnalysis;
67

78
namespace Skybrud.Essentials.Http {
@@ -186,6 +187,35 @@ public static class HttpRequestExtensions {
186187
return request;
187188
}
188189

190+
/// <summary>
191+
/// Sets the <strong>Authorization</strong> header of <paramref name="request"/> to use <strong>Basic</strong>
192+
/// authentication based on the specified <paramref name="username"/> and <paramref name="password"/>.
193+
/// </summary>
194+
/// <typeparam name="T">The type of the request - eg. <see cref="HttpRequest"/>.</typeparam>
195+
/// <param name="request">The request.</param>
196+
/// <param name="username">The username.</param>
197+
/// <param name="password">The password.</param>
198+
/// <returns>The specified <paramref name="request"/> as an instance of <typeparamref name="T"/>.</returns>
199+
[return: NotNullIfNotNull("request")]
200+
public static T? SetAuthorizationBasic<T>(this T? request, string username, string password) where T : IHttpRequest {
201+
if (request != null) request.Headers.Authorization = $"Basic {SecurityUtils.Base64Encode($"{username}:{password}")}";
202+
return request;
203+
}
204+
205+
/// <summary>
206+
/// Sets the <strong>Authorization</strong> header of <paramref name="request"/> using the specified
207+
/// <strong>Bearer</strong> <paramref name="token"/>.
208+
/// </summary>
209+
/// <typeparam name="T">The type of the request - eg. <see cref="HttpRequest"/>.</typeparam>
210+
/// <param name="request">The request.</param>
211+
/// <param name="token">The bearer token.</param>
212+
/// <returns>The specified <paramref name="request"/> as an instance of <typeparamref name="T"/>.</returns>
213+
[return: NotNullIfNotNull("request")]
214+
public static T? SetAuthorizationBearer<T>(this T? request, string token) where T : IHttpRequest {
215+
if (request != null) request.Headers.Authorization = $"Bearer {token}";
216+
return request;
217+
}
218+
189219
/// <summary>
190220
/// Sets the <strong>ContentType</strong> header of <paramref name="request"/>.
191221
/// </summary>

0 commit comments

Comments
 (0)