Skip to content

Commit

Permalink
Merge pull request #39 from Purdue-ACM-SIGAPP/dakshesh-login-test
Browse files Browse the repository at this point in the history
API Authentication using Okta Auth0 [DO NOT MERGE]
  • Loading branch information
AndrewZacharyLiu authored Nov 17, 2024
2 parents e9aaec2 + 5e90f1a commit 117e371
Show file tree
Hide file tree
Showing 7 changed files with 138 additions and 13 deletions.
48 changes: 47 additions & 1 deletion Controllers/MyController.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,61 @@
using Microsoft.AspNetCore.Mvc;
using Twilio;
using Twilio.Rest.Verify.V2.Service;
using dotenv.net;
using Microsoft.AspNetCore.Authorization;

namespace SimpleWebAppReact.Controllers
{
{

[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
[HttpGet("message")] // Define the route for this action
[Authorize]
public IActionResult GetMessage()
{
return Ok(new { message = "Hello from ASP.NET Core!" });
}

// Send Twillio Verification Email

[HttpGet("send-verification-email")]
public async Task<IActionResult> SendVerificationEmail()
{
DotEnv.Load();

string accountSid = Environment.GetEnvironmentVariable("TWILLIO_ACCOUNT_SID");

Console.WriteLine(accountSid);

string authToken = Environment.GetEnvironmentVariable("TWILLIO_AUTH_TOKEN");
string testRecipient = Environment.GetEnvironmentVariable("TEST_RECIPIENT");
string templateId = Environment.GetEnvironmentVariable("TWILLIO_TEMPLATE_ID");
string testName = Environment.GetEnvironmentVariable("TEST_NAME");
string serviceSid = Environment.GetEnvironmentVariable("TWILLIO_SERVICE_SID");

TwilioClient.Init(accountSid, authToken);

var verification = await VerificationResource.CreateAsync(
channel: "email",
to: testRecipient,
channelConfiguration: new Dictionary<
string,
Object>() { { "template_id", templateId }, { "from", testRecipient }, { "from_name", testName } },
pathServiceSid: serviceSid);

Console.WriteLine(verification.Sid);
if (verification.Status == "pending")
{
return Ok(new { message = "Verification email sent successfully" });
}
else
{
return BadRequest(new { message = "Failed to send verification email" });
}
}
}


}
24 changes: 24 additions & 0 deletions HasScopeHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.AspNetCore.Authorization;
namespace SimpleWebAppReact;
public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
HasScopeRequirement requirement
) {
// If user does not have the scope claim, get out of here
if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))
return Task.CompletedTask;


// Split the scopes string into an array
var scopes = context.User

Check warning on line 15 in HasScopeHandler.cs

View workflow job for this annotation

GitHub Actions / test

Dereference of a possibly null reference.
.FindFirst(c => c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');

// Succeed if the scope array contains the required scope
if (scopes.Any(s => s == requirement.Scope))
context.Succeed(requirement);

return Task.CompletedTask;
}
}
13 changes: 13 additions & 0 deletions HasScopeRequirement.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using Microsoft.AspNetCore.Authorization;

public class HasScopeRequirement : IAuthorizationRequirement
{
public string Issuer { get; }
public string Scope { get; }

public HasScopeRequirement(string scope, string issuer)
{
Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
}
}
24 changes: 22 additions & 2 deletions Program.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
using System.Diagnostics;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
using SimpleWebAppReact;
using SimpleWebAppReact.Services;

var builder = WebApplication.CreateBuilder(args);
Expand All @@ -13,6 +17,21 @@
builder.Services.AddSingleton<MongoDbService>();
builder.Services.AddHttpClient<BuildingOutlineService>();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://dev-mkdb0weeluguzopu.us.auth0.com/";
options.Audience = "http://localhost:5128";
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier
};
});

builder.Services.AddAuthorization();
builder.Services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();


var app = builder.Build();

// Configure the HTTP request pipeline.
Expand All @@ -30,7 +49,8 @@
app.UseRouting();

app.UseCors("AllowAll"); // Enable CORS

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
Expand Down
7 changes: 7 additions & 0 deletions SimpleWebAppReact.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,21 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Auth0.AspNetCore.Authentication" Version="1.4.1" />
<PackageReference Include="dotenv.net" Version="3.2.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
<PackageReference Include="FuzzySharp" Version="2.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.33" />
<PackageReference Include="MongoDB.Driver" Version="2.28.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.1.2" />
<PackageReference Include="Twilio" Version="7.5.0" />
<PackageReference Include="xunit" Version="2.9.0" />
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="7.0.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.0.0" />
</ItemGroup>

<ItemGroup>
Expand Down
29 changes: 20 additions & 9 deletions Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
namespace SimpleWebAppReact;

/// <summary>
/// runs startup commands, builds front end, CORS
/// </summary>
Expand All @@ -11,13 +11,14 @@ public class Startup
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHttpClient();

services.AddSingleton<BuildingOutlineService>();

// Configure CORS to allow requests from React Native frontend
Expand All @@ -30,6 +31,20 @@ public void ConfigureServices(IServiceCollection services)
.AllowAnyHeader();
});
});
services.AddMvc();

// 1. Add Authentication Services
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.Authority = "https://dev-mkdb0weeluguzopu.us.auth0.com/";
options.Audience = "http://localhost:5128";
});

services.AddAuthorization();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
Expand All @@ -45,15 +60,11 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseStaticFiles();

// Enable CORS
app.UseRouting();
app.UseCors("AllowAll");

app.UseAuthorization();

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
Expand Down
6 changes: 5 additions & 1 deletion appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"Auth0": {
"Domain": "https://dev-mkdb0weeluguzopu.us.auth0.com/",
"Audience": "http://localhost:5128"
}
}

0 comments on commit 117e371

Please sign in to comment.