Skip to content

Commit 63d62a2

Browse files
committed
SampleWebApi project added.
1 parent d2e9f1f commit 63d62a2

12 files changed

+298
-0
lines changed

Mihir.AspNetCore.Authentication.Basic.sln

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
1111
README.md = README.md
1212
EndProjectSection
1313
EndProject
14+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SampleWebApi", "SampleWebApi\SampleWebApi.csproj", "{1DB7BD52-D1E0-4248-819F-8424AFF55689}"
15+
EndProject
1416
Global
1517
GlobalSection(SolutionConfigurationPlatforms) = preSolution
1618
Debug|Any CPU = Debug|Any CPU
@@ -21,6 +23,10 @@ Global
2123
{F8FEFB06-9F93-4F50-8530-80F5C0A677FC}.Debug|Any CPU.Build.0 = Debug|Any CPU
2224
{F8FEFB06-9F93-4F50-8530-80F5C0A677FC}.Release|Any CPU.ActiveCfg = Release|Any CPU
2325
{F8FEFB06-9F93-4F50-8530-80F5C0A677FC}.Release|Any CPU.Build.0 = Release|Any CPU
26+
{1DB7BD52-D1E0-4248-819F-8424AFF55689}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27+
{1DB7BD52-D1E0-4248-819F-8424AFF55689}.Debug|Any CPU.Build.0 = Debug|Any CPU
28+
{1DB7BD52-D1E0-4248-819F-8424AFF55689}.Release|Any CPU.ActiveCfg = Release|Any CPU
29+
{1DB7BD52-D1E0-4248-819F-8424AFF55689}.Release|Any CPU.Build.0 = Release|Any CPU
2430
EndGlobalSection
2531
GlobalSection(SolutionProperties) = preSolution
2632
HideSolutionNode = FALSE
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
using Microsoft.AspNetCore.Mvc;
2+
using System.Collections.Generic;
3+
4+
namespace SampleWebApi.Controllers
5+
{
6+
[Route("api/[controller]")]
7+
public class ValuesController : Controller
8+
{
9+
// GET api/values
10+
[HttpGet]
11+
public IEnumerable<string> Get()
12+
{
13+
return new string[] { "value1", "value2" };
14+
}
15+
16+
// GET api/values/5
17+
[HttpGet("{id}")]
18+
public string Get(int id)
19+
{
20+
return "value";
21+
}
22+
23+
// POST api/values
24+
[HttpPost]
25+
public void Post([FromBody]string value)
26+
{
27+
}
28+
29+
// PUT api/values/5
30+
[HttpPut("{id}")]
31+
public void Put(int id, [FromBody]string value)
32+
{
33+
}
34+
35+
// DELETE api/values/5
36+
[HttpDelete("{id}")]
37+
public void Delete(int id)
38+
{
39+
}
40+
}
41+
}

SampleWebApi/Models/User.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
namespace SampleWebApi.Models
2+
{
3+
/// <summary>
4+
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
5+
/// </summary>
6+
public class User
7+
{
8+
public string Username { get; set; }
9+
public string Password { get; set; }
10+
}
11+
}

SampleWebApi/Program.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
using Microsoft.AspNetCore;
2+
using Microsoft.AspNetCore.Hosting;
3+
4+
namespace SampleWebApi
5+
{
6+
public class Program
7+
{
8+
public static void Main(string[] args)
9+
{
10+
BuildWebHost(args).Run();
11+
}
12+
13+
public static IWebHost BuildWebHost(string[] args) =>
14+
WebHost.CreateDefaultBuilder(args)
15+
.UseStartup<Startup>()
16+
.Build();
17+
}
18+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
{
2+
"iisSettings": {
3+
"windowsAuthentication": false,
4+
"anonymousAuthentication": true,
5+
"iisExpress": {
6+
"applicationUrl": "http://localhost:3920/",
7+
"sslPort": 0
8+
}
9+
},
10+
"profiles": {
11+
"IIS Express": {
12+
"commandName": "IISExpress",
13+
"launchBrowser": true,
14+
"launchUrl": "api/values",
15+
"environmentVariables": {
16+
"ASPNETCORE_ENVIRONMENT": "Development"
17+
}
18+
},
19+
"SampleWebApi": {
20+
"commandName": "Project",
21+
"launchBrowser": true,
22+
"launchUrl": "api/values",
23+
"environmentVariables": {
24+
"ASPNETCORE_ENVIRONMENT": "Development"
25+
},
26+
"applicationUrl": "http://localhost:3921/"
27+
}
28+
}
29+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
using SampleWebApi.Models;
2+
using System.Collections.Generic;
3+
using System.Threading.Tasks;
4+
5+
namespace SampleWebApi.Repositories
6+
{
7+
/// <summary>
8+
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
9+
/// </summary>
10+
public interface IUserRepository
11+
{
12+
Task<User> GetUserByUsername(string username);
13+
Task<IEnumerable<User>> GetUsers();
14+
}
15+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System.Collections.Generic;
2+
using System.Linq;
3+
using System.Threading.Tasks;
4+
using SampleWebApi.Models;
5+
6+
namespace SampleWebApi.Repositories
7+
{
8+
/// <summary>
9+
/// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
10+
/// </summary>
11+
public class InMemoryUserRepository : IUserRepository
12+
{
13+
private List<User> _users = new List<User>
14+
{
15+
new User { Username = "TestUser1", Password = "1234" },
16+
new User { Username = "TestUser2", Password = "1234" },
17+
new User { Username = "TestUser3", Password = "1234" },
18+
new User { Username = "TestUser4", Password = "1234" }
19+
};
20+
21+
22+
public Task<User> GetUserByUsername(string username)
23+
{
24+
return Task.FromResult(_users.FirstOrDefault(u => u.Username == username));
25+
}
26+
27+
public Task<IEnumerable<User>> GetUsers()
28+
{
29+
return Task.FromResult<IEnumerable<User>>(_users);
30+
}
31+
}
32+
}

SampleWebApi/SampleWebApi.csproj

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<Project Sdk="Microsoft.NET.Sdk.Web">
2+
3+
<PropertyGroup>
4+
<TargetFramework>netcoreapp2.0</TargetFramework>
5+
</PropertyGroup>
6+
7+
<ItemGroup>
8+
<Folder Include="wwwroot\" />
9+
</ItemGroup>
10+
11+
<ItemGroup>
12+
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" />
13+
<PackageReference Include="Mihir.AspNetCore.Authentication.Basic" Version="1.0.2" />
14+
</ItemGroup>
15+
16+
<ItemGroup>
17+
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" />
18+
</ItemGroup>
19+
20+
</Project>
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using Microsoft.Extensions.Logging;
4+
using Mihir.AspNetCore.Authentication.Basic;
5+
using SampleWebApi.Repositories;
6+
7+
namespace SampleWebApi.Services
8+
{
9+
internal class BasicUserValidationService : IBasicUserValidationService
10+
{
11+
private readonly ILogger<BasicUserValidationService> _logger;
12+
private readonly IUserRepository _userRepository;
13+
14+
public BasicUserValidationService(ILogger<BasicUserValidationService> logger, IUserRepository userRepository)
15+
{
16+
_logger = logger;
17+
_userRepository = userRepository;
18+
}
19+
20+
public async Task<bool> IsValidAsync(string username, string password)
21+
{
22+
try
23+
{
24+
// NOTE: DO NOT USE THIS IMPLEMENTATION. THIS IS FOR DEMO PURPOSE ONLY
25+
// Write your implementation here and return true or false depending on the validation..
26+
var user = await _userRepository.GetUserByUsername(username);
27+
var isValid = user.Password == password;
28+
return isValid;
29+
}
30+
catch (Exception e)
31+
{
32+
_logger.LogError(e, e.Message);
33+
throw;
34+
}
35+
}
36+
}
37+
}

SampleWebApi/Startup.cs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
using Microsoft.AspNetCore.Authorization;
2+
using Microsoft.AspNetCore.Builder;
3+
using Microsoft.AspNetCore.Hosting;
4+
using Microsoft.AspNetCore.Mvc.Authorization;
5+
using Microsoft.AspNetCore.Rewrite;
6+
using Microsoft.Extensions.Configuration;
7+
using Microsoft.Extensions.DependencyInjection;
8+
using Mihir.AspNetCore.Authentication.Basic;
9+
using SampleWebApi.Repositories;
10+
using SampleWebApi.Services;
11+
12+
namespace SampleWebApi
13+
{
14+
public class Startup
15+
{
16+
public Startup(IConfiguration configuration)
17+
{
18+
Configuration = configuration;
19+
}
20+
21+
public IConfiguration Configuration { get; }
22+
23+
// This method gets called by the runtime. Use this method to add services to the container.
24+
public void ConfigureServices(IServiceCollection services)
25+
{
26+
// Add User repository to the dependency container.
27+
services.AddTransient<IUserRepository, InMemoryUserRepository>();
28+
29+
// Add the Basic scheme authentication here..
30+
// AddBasic extension takes an implementation of IBasicUserValidationService for validating the username and password.
31+
// It also requires Realm to be set in the options.
32+
services.AddAuthentication(BasicDefaults.AuthenticationScheme)
33+
.AddBasic<BasicUserValidationService>(options => { options.Realm = "Sample Web API"; });
34+
35+
services.AddMvc(options =>
36+
{
37+
// ALWAYS USE HTTPS (SSL) protocol in production when using Basic authentication.
38+
//options.Filters.Add<RequireHttpsAttribute>();
39+
40+
// All the requests will need to be authorized.
41+
// Alternatively, add [Authorize] attribute to Controller or Action Method where necessary.
42+
options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
43+
}
44+
).AddXmlSerializerFormatters(); // To enable XML along with JSON
45+
}
46+
47+
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
48+
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
49+
{
50+
if (env.IsDevelopment())
51+
{
52+
app.UseDeveloperExceptionPage();
53+
}
54+
else
55+
{
56+
// ALWAYS USE HTTPS (SSL) protocol in production when using Basic authentication.
57+
app.UseRewriter(new RewriteOptions().AddRedirectToHttpsPermanent());
58+
}
59+
60+
app.UseAuthentication();
61+
app.UseMvc();
62+
}
63+
}
64+
}

0 commit comments

Comments
 (0)