-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #15 from caiolombello/master
Add token authentication feature and adjust tests
- Loading branch information
Showing
25 changed files
with
1,460 additions
and
318 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,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net6.0</TargetFramework> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.18" /> | ||
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" /> | ||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Core" Version="1.1.0" /> | ||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> | ||
</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,67 @@ | ||
using Microsoft.AspNetCore.Mvc; | ||
using Microsoft.IdentityModel.Tokens; | ||
using System; | ||
using System.IdentityModel.Tokens.Jwt; | ||
using System.Security.Claims; | ||
using System.Text; | ||
|
||
namespace AspNetAuthExample.Controllers | ||
{ | ||
// Define the route for the API controller | ||
[Route("api/[controller]")] | ||
[ApiController] | ||
public class AuthController : ControllerBase | ||
{ | ||
// Define the POST endpoint for login | ||
[HttpPost("login")] | ||
public IActionResult Login([FromBody] LoginModel login) | ||
{ | ||
// Check if the provided username and password match the predefined values | ||
if (login.Username == "test" && login.Password == "password") | ||
{ | ||
// Generate a JWT token if credentials are correct | ||
var token = GenerateToken(); | ||
// Return the token in the response | ||
return Ok(new { token }); | ||
} | ||
// Return Unauthorized status if credentials are incorrect | ||
return Unauthorized(); | ||
} | ||
|
||
// Method to generate a JWT token | ||
private string GenerateToken() | ||
{ | ||
// Define the security key using a secret key | ||
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yoursecretkeyheretoSignalRserver")); | ||
// Define the signing credentials using HMAC-SHA256 algorithm | ||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); | ||
|
||
// Define the claims to be included in the token | ||
var claims = new[] | ||
{ | ||
new Claim(JwtRegisteredClaimNames.Sub, "testuser"), | ||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) | ||
}; | ||
|
||
// Create the JWT token with specified claims and expiration time | ||
var token = new JwtSecurityToken( | ||
issuer: null, | ||
audience: null, | ||
claims: claims, | ||
expires: DateTime.Now.AddMinutes(30), | ||
signingCredentials: credentials); | ||
|
||
// Return the serialized token as a string | ||
return new JwtSecurityTokenHandler().WriteToken(token); | ||
} | ||
} | ||
|
||
// Model to represent the login request payload | ||
public class LoginModel | ||
{ | ||
// Username property | ||
public string Username { get; set; } | ||
// Password property | ||
public string Password { get; set; } | ||
} | ||
} |
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,22 @@ | ||
# Use the official ASP.NET Core runtime as a parent image | ||
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base | ||
WORKDIR /app | ||
EXPOSE 80 | ||
|
||
# Use the SDK image to build and publish the app | ||
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build | ||
WORKDIR /src | ||
COPY ["AspNetAuthExample.csproj", "./"] | ||
RUN dotnet restore "AspNetAuthExample.csproj" | ||
COPY . . | ||
WORKDIR "/src/." | ||
RUN dotnet build "AspNetAuthExample.csproj" -c Release -o /app/build | ||
|
||
FROM build AS publish | ||
RUN dotnet publish "AspNetAuthExample.csproj" -c Release -o /app/publish | ||
|
||
# Final stage/image | ||
FROM base AS final | ||
WORKDIR /app | ||
COPY --from=publish /app/publish . | ||
ENTRYPOINT ["dotnet", "AspNetAuthExample.dll"] |
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,44 @@ | ||
using Microsoft.AspNetCore.Authorization; | ||
using Microsoft.AspNetCore.SignalR; | ||
using System.Threading.Tasks; | ||
|
||
using AspNetAuthExample.Controllers; | ||
|
||
namespace AspNetAuthExample | ||
{ | ||
// Define a SignalR Hub for weather updates | ||
public class WeatherHub : Hub | ||
{ | ||
// Method to send a message to all connected clients | ||
public async Task SendMessage(string user, string message) | ||
{ | ||
await Clients.All.SendAsync("ReceiveMessage", user, message); | ||
} | ||
|
||
// Method to send a message to a specific group | ||
public async Task SendMessageToGroup(string groupName, string user, string message) | ||
{ | ||
await Clients.Group(groupName).SendAsync("ReceiveMessage", user, message); | ||
} | ||
|
||
// Method to add a client to a group | ||
public async Task AddToGroup(string groupName) | ||
{ | ||
await Groups.AddToGroupAsync(Context.ConnectionId, groupName); | ||
await Clients.Group(groupName).SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} has joined the group {groupName}."); | ||
} | ||
|
||
// Method to remove a client from a group | ||
public async Task RemoveFromGroup(string groupName) | ||
{ | ||
await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName); | ||
await Clients.Group(groupName).SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} has left the group {groupName}."); | ||
} | ||
|
||
// Method to send the weather forecast to all clients | ||
public async Task SendWeatherForecast(string forecast) | ||
{ | ||
await Clients.All.SendAsync("ReceiveWeatherForecast", forecast); | ||
} | ||
} | ||
} |
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 Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Hosting; | ||
|
||
namespace AspNetAuthExample | ||
{ | ||
// Main entry point of the application | ||
public class Program | ||
{ | ||
public static void Main(string[] args) | ||
{ | ||
// Build and run the host | ||
CreateHostBuilder(args).Build().Run(); | ||
} | ||
|
||
// Method to create and configure the host builder | ||
public static IHostBuilder CreateHostBuilder(string[] args) => | ||
Host.CreateDefaultBuilder(args) | ||
.ConfigureWebHostDefaults(webBuilder => | ||
{ | ||
// Specify the startup class to be used by the web host | ||
webBuilder.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,80 @@ | ||
using Microsoft.AspNetCore.Authentication.JwtBearer; | ||
using Microsoft.AspNetCore.Builder; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Hosting; | ||
using Microsoft.IdentityModel.Tokens; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
|
||
namespace AspNetAuthExample | ||
{ | ||
public class Startup | ||
{ | ||
public Startup(IConfiguration configuration) | ||
{ | ||
Configuration = configuration; | ||
} | ||
|
||
public IConfiguration Configuration { get; } | ||
|
||
// Method to configure the services for the application | ||
public void ConfigureServices(IServiceCollection services) | ||
{ | ||
services.AddControllers(); | ||
services.AddSignalR(); | ||
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) | ||
.AddJwtBearer(options => | ||
{ | ||
options.TokenValidationParameters = new TokenValidationParameters | ||
{ | ||
ValidateIssuer = false, | ||
ValidateAudience = false, | ||
ValidateLifetime = true, | ||
ValidateIssuerSigningKey = true, | ||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("yoursecretkeyheretoSignalRserver")) | ||
}; | ||
options.Events = new JwtBearerEvents | ||
{ | ||
OnMessageReceived = context => | ||
{ | ||
var accessToken = context.Request.Query["access_token"]; | ||
|
||
var path = context.HttpContext.Request.Path; | ||
if (!string.IsNullOrEmpty(accessToken) && | ||
path.StartsWithSegments("/weatherHub")) | ||
{ | ||
context.Token = accessToken; | ||
} | ||
return Task.CompletedTask; | ||
} | ||
}; | ||
}); | ||
|
||
services.AddAuthorization(); | ||
} | ||
|
||
// Method to configure the HTTP request pipeline | ||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | ||
{ | ||
if (env.IsDevelopment()) | ||
{ | ||
app.UseDeveloperExceptionPage(); | ||
} | ||
|
||
app.UseHttpsRedirection(); | ||
|
||
app.UseRouting(); | ||
|
||
app.UseAuthentication(); | ||
app.UseAuthorization(); | ||
|
||
app.UseEndpoints(endpoints => | ||
{ | ||
endpoints.MapControllers(); | ||
endpoints.MapHub<WeatherHub>("/weatherHub"); | ||
}); | ||
} | ||
} | ||
} |
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
Oops, something went wrong.