Skip to content

Commit e9bc944

Browse files
committed
- Readme updated
- Version updated - Copyright year updated
1 parent 9a0b17b commit e9bc944

File tree

3 files changed

+120
-33
lines changed

3 files changed

+120
-33
lines changed

LICENSE.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
MIT License
22

3-
Copyright (c) 2020 Mihir Dilip
3+
Copyright (c) 2021 Mihir Dilip
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal

README.md

Lines changed: 116 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,14 @@ Easy to use and very light weight Microsoft style Basic Scheme Authentication Im
33

44
[View On GitHub](https://github.com/mihirdilip/aspnetcore-authentication-basic)
55

6+
<br/>
7+
8+
## .NET (Core) Frameworks Supported
9+
.NET Framework 4.6.1 and/or NetStandard 2.0 onwards
10+
Multi targeted: net5.0; netcoreapp3.1; netcoreapp3.0; netstandard2.0; net461
11+
12+
<br/>
13+
614
## Installing
715
This library is published on NuGet. So the NuGet package can be installed directly to your project if you wish to use it without making any custom changes to the code.
816

@@ -16,37 +24,41 @@ Or by running the below command on your project.
1624
PM> Install-Package AspNetCore.Authentication.Basic
1725
```
1826

27+
<br/>
28+
1929
## Example Usage
2030

2131
Samples are available under [samples directory](samples).
2232

23-
Setting it up is quite simple. You will need basic working knowledge of ASP.NET Core 2.2 or newer to get started using this code.
33+
Setting it up is quite simple. You will need basic working knowledge of ASP.NET Core 2.0 or newer to get started using this library.
2434

25-
On [**Startup.cs**](#startupcs), as shown below, add 2 lines in *ConfigureServices* method `services.AddAuthentication(BasicDefaults.AuthenticationScheme).AddBasic<BasicUserValidationService>(options => { options.Realm = "My App"; });`. And a line `app.UseAuthentication();` in *Configure* method.
35+
There are 2 different ways of using this library to do it's job. Both ways can be mixed if required.
36+
1] Using the implementation of *IBasicUserValidationService*
37+
2] Using *BasicOptions.Events* (OnValidateCredentials delegate) which is same approach you will find on Microsoft's authentication libraries
2638

27-
Also add an implementation of *IBasicUserValidationService* as shown below in [**BasicUserValidationService.cs**](#basicuservalidationservicecs).
39+
Notes:
40+
- It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
41+
- If an implementation of IBasicUserValidationService interface is used as well as BasicOptions.Events.OnValidateCredentials delegate is also set then this delegate will be used first.
2842

29-
**NOTE: Always use HTTPS (SSL Certificate) protocol in production when using Basic authentication.**
43+
**Always use HTTPS (SSL Certificate) protocol in production when using API Key authentication.**
3044

31-
#### Startup.cs (ASP.NET Core 3.0 or newer)
45+
#### Startup.cs (ASP.NET Core 3.0 onwards)
3246

3347
```C#
3448
using AspNetCore.Authentication.Basic;
3549
public class Startup
3650
{
3751
public void ConfigureServices(IServiceCollection services)
3852
{
39-
// Add the Basic scheme authentication here..
4053
// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
41-
// If an implementation of IBasicUserValidationService interface is registered in the dependency register as well as OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of an implementation of IBasicUserValidationService.
54+
// If an implementation of IBasicUserValidationService interface is used as well as options.Events.OnValidateCredentials delegate is also set then this delegate will be used first.
55+
4256
services.AddAuthentication(BasicDefaults.AuthenticationScheme)
4357

44-
// The below AddBasic without type parameter will require OnValidateCredentials delegete on options.Events to be set unless an implementation of IBasicUserValidationService interface is registered in the dependency register.
45-
// Please note if both the delgate and validation server are set then the delegate will be used instead of BasicUserValidationService.
58+
// The below AddBasic without type parameter will require options.Events.OnValidateCredentials delegete to be set.
4659
//.AddBasic(options => { options.Realm = "My App"; });
4760
48-
// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency register.
49-
// Please note if OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of BasicUserValidationService.
61+
// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency container.
5062
.AddBasic<BasicUserValidationService>(options => { options.Realm = "My App"; });
5163

5264
services.AddControllers();
@@ -77,25 +89,23 @@ public class Startup
7789
}
7890
```
7991

80-
#### Startup.cs (ASP.NET Core 2.2)
92+
#### Startup.cs (ASP.NET Core 2.0 onwards)
8193

8294
```C#
8395
using AspNetCore.Authentication.Basic;
8496
public class Startup
8597
{
8698
public void ConfigureServices(IServiceCollection services)
8799
{
88-
// Add the Basic scheme authentication here..
89100
// It requires Realm to be set in the options if SuppressWWWAuthenticateHeader is not set.
90-
// If an implementation of IBasicUserValidationService interface is registered in the dependency register as well as OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of an implementation of IBasicUserValidationService.
101+
// If an implementation of IBasicUserValidationService interface is used as well as options.Events.OnValidateCredentials delegate is also set then this delegate will be used first.
102+
91103
services.AddAuthentication(BasicDefaults.AuthenticationScheme)
92104

93-
// The below AddBasic without type parameter will require OnValidateCredentials delegete on options.Events to be set unless an implementation of IBasicUserValidationService interface is registered in the dependency register.
94-
// Please note if both the delgate and validation server are set then the delegate will be used instead of BasicUserValidationService.
105+
// The below AddBasic without type parameter will require options.Events.OnValidateCredentials delegete to be set.
95106
//.AddBasic(options => { options.Realm = "My App"; });
96107
97-
// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency register.
98-
// Please note if OnValidateCredentials delegete on options.Events is also set then this delegate will be used instead of BasicUserValidationService.
108+
// The below AddBasic with type parameter will add the BasicUserValidationService to the dependency container.
99109
.AddBasic<BasicUserValidationService>(options => { options.Realm = "My App"; });
100110

101111
services.AddMvc();
@@ -144,60 +154,70 @@ public class BasicUserValidationService : IBasicUserValidationService
144154
}
145155
```
146156

157+
<br/>
158+
<br/>
159+
147160
## Configuration (BasicOptions)
148-
#### Realm
161+
162+
### Realm
149163
Required to be set if SuppressWWWAuthenticateHeader is not set to true. It is used with WWW-Authenticate response header when challenging un-authenticated requests.
150164

151-
#### SuppressWWWAuthenticateHeader
165+
### SuppressWWWAuthenticateHeader
152166
Default value is false.
153167
When set to true, it will NOT return WWW-Authenticate response header when challenging un-authenticated requests.
154168
When set to false, it will return WWW-Authenticate response header when challenging un-authenticated requests.
155169

156-
#### IgnoreAuthenticationIfAllowAnonymous
170+
### IgnoreAuthenticationIfAllowAnonymous (available on ASP.NET Core 3.0 onwards)
157171
Default value is false.
158172
If set to true, it checks if AllowAnonymous filter on controller action or metadata on the endpoint which, if found, it does not try to authenticate the request.
159173

160-
#### Events
174+
### Events
161175
The object provided by the application to process events raised by the basic authentication middleware.
162176
The application may implement the interface fully, or it may create an instance of BasicEvents and assign delegates only to the events it wants to process.
163-
- ##### OnValidateCredentials
177+
- #### OnValidateCredentials
164178
A delegate assigned to this property will be invoked just before validating credentials.
165179
You must provide a delegate for this property for authentication to occur.
166180
In your delegate you should either call context.ValidationSucceeded() which will handle construction of authentication principal from the user details which will be assiged the context.Principal property and call context.Success(), or construct an authentication principal from the user details & attach it to the context.Principal property and finally call context.Success() method.
167181
If only context.Principal property set without calling context.Success() method then, Success() method is automaticalled called.
168182

169-
- ##### OnAuthenticationSucceeded
183+
- #### OnAuthenticationSucceeded
170184
A delegate assigned to this property will be invoked when the authentication succeeds. It will not be called if OnValidateCredentials delegate is assigned.
171185
It can be used for adding claims, headers, etc to the response.
172186

173-
- ##### OnAuthenticationFailed
187+
- #### OnAuthenticationFailed
174188
A delegate assigned to this property will be invoked when the authentication fails.
175189

176-
- ##### OnHandleChallenge
190+
- #### OnHandleChallenge
177191
A delegate assigned to this property will be invoked before a challenge is sent back to the caller when handling unauthorized response.
178192
Only use this if you know what you are doing and if you want to use custom implementation. Set the delegate to deal with 401 challenge concerns, if an authentication scheme in question deals an authentication interaction as part of it's request flow. (like adding a response header, or changing the 401 result to 302 of a login page or external sign-in location.)
179193
Call context.Handled() at the end so that any default logic for this challenge will be skipped.
180194

181-
- ##### OnHandleForbidden
195+
- #### OnHandleForbidden
182196
A delegate assigned to this property will be invoked if Authorization fails and results in a Forbidden response.
183197
Only use this if you know what you are doing and if you want to use custom implementation.
184198
Set the delegate to handle Forbid.
185199
Call context.Handled() at the end so that any default logic will be skipped.
186200

201+
<br/>
202+
<br/>
187203

188204
## Additional Notes
189-
Please note that, by default, with ASP.NET Core, all the requests are not challenged for authentication. So don't worry if your *BasicUserValidationService* is not hit when you don't pass the required basic authentication details with the request. It is a normal behaviour. ASP.NET Core challenges authentication only when it is specifically told to do so either by decorating controller/method with *[Authorize]* filter attribute or by some other means.
205+
206+
### Basic Authentication Not Challenged
207+
With ASP.NET Core, all the requests are not challenged for authentication by default. So don't worry if your *BasicUserValidationService* is not hit when you don't pass the required basic authentication details with the request. It is a normal behaviour. ASP.NET Core challenges authentication only when it is specifically told to do so either by decorating controller/method with *[Authorize]* filter attribute or by some other means.
190208

191209
However, if you want all the requests to challenge authentication by default, depending on what you are using, you can add the below options line to *ConfigureServices* method on *Startup* class.
192210

193211
```C#
212+
// On ASP.NET Core 3.0 onwards
194213
services.AddAuthorization(options =>
195214
{
196215
options.FallbackPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
197216
});
198217

199218
// OR
200219
220+
// On ASP.NET Core 2.0 onwards
201221
services.AddMvc(options =>
202222
{
203223
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
@@ -207,6 +227,7 @@ services.AddMvc(options =>
207227
If you are not using MVC but, using Endpoints on ASP.NET Core 3.0 or newer, you can add a chain method `.RequireAuthorization()` to the endpoint map under *Configure* method on *Startup* class as shown below.
208228

209229
```C#
230+
// ASP.NET Core 3.0 onwards
210231
app.UseEndpoints(endpoints =>
211232
{
212233
endpoints.MapGet("/", async context =>
@@ -216,6 +237,73 @@ app.UseEndpoints(endpoints =>
216237
});
217238
```
218239

240+
### Multiple Authentication Schemes
241+
ASP.NET Core supports adding multiple authentication schemes which this library also supports. Just need to use the extension method which takes scheme name as parameter. The rest is all same. This can be achieved in many different ways. Below is just a quick rough example.
242+
243+
Please note that scheme name parameter can be any string you want.
244+
245+
```C#
246+
public void ConfigureServices(IServiceCollection services)
247+
{
248+
services.AddTransient<IUserRepository, InMemoryUserRepository>();
249+
250+
services.AddAuthentication("Scheme1")
251+
252+
.AddBasic<BasicUserValidationService>("Scheme1", options => { options.Realm = "My App"; })
253+
254+
.AddBasic<BasicUserValidationService_2>("Scheme2", options => { options.Realm = "My App"; })
255+
256+
.AddBasic("Scheme3", options =>
257+
{
258+
options.Realm = "My App";
259+
options.Events = new BasicEvents
260+
{
261+
OnValidateCredentials = async (context) =>
262+
{
263+
var userRepository = context.HttpContext.RequestServices.GetRequiredService<IUserRepository>();
264+
var user = await userRepository.GetUserByUsername(context.Username);
265+
var isValid = user != null && user.Password == context.Password;
266+
if (isValid)
267+
{
268+
context.Response.Headers.Add("ValidationCustomHeader", "From OnValidateCredentials");
269+
var claims = new[]
270+
{
271+
new Claim("CustomClaimType", "Custom Claim Value - from OnValidateCredentials")
272+
};
273+
context.ValidationSucceeded(claims); // claims are optional
274+
}
275+
else
276+
{
277+
context.ValidationFailed();
278+
}
279+
}
280+
}
281+
});
282+
283+
services.AddControllers();
284+
285+
services.AddAuthorization(options =>
286+
{
287+
options.FallbackPolicy = new AuthorizationPolicyBuilder("Scheme1", "Scheme2", "Scheme3").RequireAuthenticatedUser().Build();
288+
});
289+
}
290+
```
291+
292+
<br/>
293+
<br/>
294+
295+
## Release Notes
296+
| Version | &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Notes |
297+
|---------|-------|
298+
|5.1.0 | <ul><li>Visibility of all the handlers changed to public</li><li>Tests added</li><li>Readme updated</li><li>Copyright year updated on License</li></ul> |
299+
|5.0.0 | <ul><li>Net 5.0 target framework added</li><li>IgnoreAuthenticationIfAllowAnonymous added to the ApiKeyOptions from netcoreapp3.0 onwards [#15](https://github.com/mihirdilip/aspnetcore-authentication-apikey/issues/15)</li></ul> |
300+
|3.1.1 | <ul><li>Fixed issue with resolving of IBasicUserValidationService implementation when using multiple schemes</li></ul> |
301+
|3.1.0 | <ul><li>Multitarget framework support added</li><li>Strong Name Key support added</li><li>Source Link support added</li><li>SuppressWWWAuthenticateHeader added to configure options</li><li>Events added to configure options</li></ul> |
302+
|2.2.0 | <ul><li>Basic Authentication Implementation for ASP.NET Core</li></ul> |
303+
304+
<br/>
305+
<br/>
306+
219307
## References
220308
- [RFC 7617: Technical spec for HTTP Basic](https://tools.ietf.org/html/rfc7617)
221309
- [ASP.NET Core Security documentation](https://docs.microsoft.com/en-us/aspnet/core/security)

src/AspNetCore.Authentication.Basic/AspNetCore.Authentication.Basic.csproj

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@
22

33
<PropertyGroup>
44
<TargetFrameworks>net5.0;netcoreapp3.1;netcoreapp3.0;netstandard2.0;net461</TargetFrameworks>
5-
<Version>5.0.0</Version>
5+
<Version>5.1.0</Version>
66
<RepositoryUrl>https://github.com/mihirdilip/aspnetcore-authentication-basic/tree/$(Version)</RepositoryUrl>
77
<PackageProjectUrl>https://github.com/mihirdilip/aspnetcore-authentication-basic/tree/$(Version)</PackageProjectUrl>
88
<PackageTags>aspnetcore, security, authentication, microsoft, microsoft.aspnetcore.authentication, microsoft-aspnetcore-authentication, microsoft.aspnetcore.authentication.basic, microsoft-aspnetcore-authentication-basic, asp-net-core, netstandard, netstandard20, basic-authentication, basicauthentication, dotnetcore, dotnetcore3.1, net5, net5.0, asp-net-core-basic-authentication, aspnetcore-basic-authentication, net5-basic-authentication, asp-net-core-authentication, aspnetcore-authentication, net5-authentication, asp, aspnet, basic, authentication-scheme</PackageTags>
9-
<PackageReleaseNotes>- .Net 5.0 target framework added
10-
- IgnoreAuthenticationIfAllowAnonymous added to the BasicOptions from netcoreapp3.0 onwards
9+
<PackageReleaseNotes>- Visibility of all the handlers changed to public
1110
</PackageReleaseNotes>
1211
<Description>Easy to use and very light weight Microsoft style Basic Scheme Authentication implementation for ASP.NET Core.</Description>
1312
<Authors>Mihir Dilip</Authors>
1413
<Company>Mihir Dilip</Company>
15-
<Copyright>Copyright (c) 2020 Mihir Dilip</Copyright>
14+
<Copyright>Copyright (c) 2021 Mihir Dilip</Copyright>
1615
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
1716
<Title>$(AssemblyName)</Title>
1817
<RepositoryType>git</RepositoryType>

0 commit comments

Comments
 (0)