-
Notifications
You must be signed in to change notification settings - Fork 35
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
#218 - Starting with API project and JWT authentication.
- Loading branch information
Showing
9 changed files
with
300 additions
and
0 deletions.
There are no files selected for viewing
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,64 @@ | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.IdentityModel.Tokens; | ||
using Neptuo; | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IdentityModel.Tokens.Jwt; | ||
using System.Linq; | ||
using System.Security.Claims; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
|
||
namespace Money.Controllers | ||
{ | ||
[Route("api/user/login")] | ||
[ApiController] | ||
public class UserLoginController : ControllerBase | ||
{ | ||
public class LoginModel | ||
{ | ||
public string UserName { get; set; } | ||
public string Password { get; set; } | ||
} | ||
|
||
private readonly IConfiguration configuration; | ||
|
||
public UserLoginController(IConfiguration configuration) | ||
{ | ||
Ensure.NotNull(configuration, "configuration"); | ||
this.configuration = configuration.GetSection("Jwt"); | ||
} | ||
|
||
[HttpPost] | ||
public IActionResult Post([FromBody] LoginModel model) | ||
{ | ||
if (model.UserName == "admin" && model.Password == "admin") | ||
{ | ||
var claims = new[] | ||
{ | ||
new Claim(ClaimTypes.Name, model.UserName) | ||
}; | ||
|
||
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["SecurityKey"])); | ||
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); | ||
var expiry = DateTime.Now.AddDays(Convert.ToInt32(configuration["ExpiryInDays"])); | ||
|
||
var token = new JwtSecurityToken( | ||
configuration["Issuer"], | ||
configuration["Issuer"], | ||
claims, | ||
expires: expiry, | ||
signingCredentials: creds | ||
); | ||
|
||
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler(); | ||
string serializedToken = handler.WriteToken(token); | ||
|
||
return base.Ok(new { token = serializedToken }); | ||
} | ||
|
||
return BadRequest("Username and password are invalid."); | ||
} | ||
} | ||
} |
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,47 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace Money.Api.Controllers | ||
{ | ||
[Route("api/[controller]")] | ||
[ApiController] | ||
[Authorize] | ||
public class ValuesController : ControllerBase | ||
{ | ||
// GET api/values | ||
[HttpGet] | ||
public ActionResult<IEnumerable<string>> Get() | ||
{ | ||
return new string[] { "value1", "value2" }; | ||
} | ||
|
||
// GET api/values/5 | ||
[HttpGet("{id}")] | ||
public ActionResult<string> Get(int id) | ||
{ | ||
return "value"; | ||
} | ||
|
||
// POST api/values | ||
[HttpPost] | ||
public void Post([FromBody] string value) | ||
{ | ||
} | ||
|
||
// PUT api/values/5 | ||
[HttpPut("{id}")] | ||
public void Put(int id, [FromBody] string value) | ||
{ | ||
} | ||
|
||
// DELETE api/values/5 | ||
[HttpDelete("{id}")] | ||
public void Delete(int id) | ||
{ | ||
} | ||
} | ||
} |
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,23 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>netcoreapp2.2</TargetFramework> | ||
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.App" /> | ||
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\Neptuo\Neptuo.csproj" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Content Update="appsettings.Development.json"> | ||
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> | ||
</Content> | ||
</ItemGroup> | ||
|
||
</Project> |
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,24 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.IO; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Money.Api | ||
{ | ||
public class Program | ||
{ | ||
public static void Main(string[] args) | ||
{ | ||
CreateWebHostBuilder(args).Build().Run(); | ||
} | ||
|
||
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => | ||
WebHost.CreateDefaultBuilder(args) | ||
.UseStartup<Startup>(); | ||
} | ||
} |
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,30 @@ | ||
{ | ||
"$schema": "http://json.schemastore.org/launchsettings.json", | ||
"iisSettings": { | ||
"windowsAuthentication": false, | ||
"anonymousAuthentication": true, | ||
"iisExpress": { | ||
"applicationUrl": "http://localhost:63803", | ||
"sslPort": 0 | ||
} | ||
}, | ||
"profiles": { | ||
"IIS Express": { | ||
"commandName": "IISExpress", | ||
"launchBrowser": true, | ||
"launchUrl": "api/values", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
}, | ||
"Money.Api": { | ||
"commandName": "Project", | ||
"launchBrowser": true, | ||
"launchUrl": "api/values", | ||
"applicationUrl": "http://localhost:5000", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
} | ||
} | ||
} |
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,70 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Authentication.JwtBearer; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.IdentityModel.Tokens; | ||
|
||
namespace Money.Api | ||
{ | ||
public class Startup | ||
{ | ||
public IConfiguration Configuration { get; } | ||
|
||
public Startup(IConfiguration configuration) => Configuration = configuration; | ||
|
||
public void ConfigureServices(IServiceCollection services) | ||
{ | ||
services | ||
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) | ||
.AddJwtBearer(options => | ||
{ | ||
IConfiguration jwtConfiguration = Configuration.GetSection("Jwt"); | ||
|
||
options.TokenValidationParameters = new TokenValidationParameters | ||
{ | ||
ValidateIssuer = true, | ||
ValidateAudience = true, | ||
ValidateLifetime = true, | ||
ValidateIssuerSigningKey = true, | ||
ValidIssuer = jwtConfiguration["Issuer"], | ||
ValidAudience = jwtConfiguration["Issuer"], | ||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfiguration["SecurityKey"])) | ||
}; | ||
|
||
options.Events = new JwtBearerEvents() | ||
{ | ||
OnAuthenticationFailed = c => | ||
{ | ||
c.NoResult(); | ||
|
||
c.Response.StatusCode = 401; | ||
c.Response.ContentType = "text/plain"; | ||
|
||
return c.Response.WriteAsync("There was an issue authorizing you."); | ||
} | ||
}; | ||
}); | ||
|
||
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); | ||
} | ||
|
||
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | ||
{ | ||
if (env.IsDevelopment()) | ||
{ | ||
app.UseDeveloperExceptionPage(); | ||
} | ||
|
||
app.UseAuthentication(); | ||
app.UseMvc(); | ||
} | ||
} | ||
} |
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,15 @@ | ||
{ | ||
"Logging": { | ||
"IncludeScopes": false, | ||
"LogLevel": { | ||
"Default": "Debug", | ||
"System": "Information", | ||
"Microsoft": "Information" | ||
} | ||
}, | ||
"Jwt": { | ||
"SecurityKey": "abcdefghijklmnop", | ||
"Issuer": "https://localhost", | ||
"ExpiryInDays": 14 | ||
} | ||
} |
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,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Warning" | ||
} | ||
}, | ||
"AllowedHosts": "*" | ||
} |