Skip to content

Commit

Permalink
Merge pull request #52 from Purdue-ACM-SIGAPP/swagger-update
Browse files Browse the repository at this point in the history
Swagger update
  • Loading branch information
AndrewZacharyLiu authored Jan 7, 2025
2 parents d07a255 + f322750 commit 8e6b1b6
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 40 deletions.
87 changes: 66 additions & 21 deletions Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using RestSharp;

namespace SimpleWebAppReact.Controllers;

using Microsoft.AspNetCore.Mvc;
Expand All @@ -18,34 +22,75 @@ public AuthController(IHttpClientFactory httpClientFactory, IConfiguration confi
_httpClientFactory = httpClientFactory;
_configuration = configuration;
}

[HttpPost("get-token")]
public async Task<IActionResult> GetToken([FromBody] LoginRequest request)


[HttpGet("whoami")]
[Authorize] // Ensure the user is authenticated
public IActionResult GetWho()
{
var client = _httpClientFactory.CreateClient("Okta");

var body = new StringBuilder();
body.Append($"grant_type=password");
body.Append($"&username={request.Username}");
body.Append($"&password={request.Password}");
body.Append($"&scope=openid");
var claims = User.Claims.Select(c => new { c.Type, c.Value });
return Ok(new
{
Message = "User info retrieved successfully.",
Claims = claims
});
}

[HttpGet("get-user-id")]
[Authorize]
public IActionResult GetUserId()
{
// Retrieve the `NameIdentifier` claim value
var userId = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

var content = new StringContent(body.ToString(), Encoding.UTF8, "application/x-www-form-urlencoded");
if (userId == null)
{
return Unauthorized(new { Message = "User ID not found in claims." });
}

var response = await client.PostAsync("v1/token", content);
return Ok(new
{
Message = "User ID retrieved successfully.",
UserId = userId
});
}
[Authorize]
[HttpGet("debug-claims")]
public IActionResult DebugClaims()
{
var claims = User.Claims.Select(c => new { c.Type, c.Value }).ToList();
return Ok(claims);
}
[HttpGet("roles")]
[Authorize]
public IActionResult GetUserRoles()
{
// Extract roles from the current user's identity
var roles = User.Claims
.Where(c => c.Type == ClaimTypes.Role) // Use ClaimTypes.Role to fetch role claims
.Select(c => c.Value)
.ToList();

if (response.IsSuccessStatusCode)
if (roles.Count == 0)
{
var tokenResponse = await response.Content.ReadAsStringAsync();
return Ok(tokenResponse);
return NotFound(new
{
Message = "No roles found for the user."
});
}

return BadRequest("Failed to retrieve token");
return Ok(new
{
Message = "User roles retrieved successfully.",
Roles = roles
});
}

[Authorize(Roles = "test")]
[HttpGet("gatekeep-test")]
public IActionResult GatekeepTest()
{
return Ok();
}
}

public class LoginRequest
{
public string Username { get; set; }
public string Password { get; set; }
}
38 changes: 30 additions & 8 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,37 @@
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
.AddJwtBearer(options =>
{
NameClaimType = ClaimTypes.NameIdentifier
};
});
options.Authority = "https://dev-2gowyyl3kin685ua.us.auth0.com/";
options.Audience = "http://localhost:5128";
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.NameIdentifier,
RoleClaimType = "https://my-app.example.com/roles"
};

options.Events = new JwtBearerEvents
{
OnTokenValidated = async context =>

Check warning on line 64 in Program.cs

View workflow job for this annotation

GitHub Actions / test

This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
{
var claimsIdentity = context.Principal.Identity as ClaimsIdentity;

Check warning on line 66 in Program.cs

View workflow job for this annotation

GitHub Actions / test

Dereference of a possibly null reference.
if (claimsIdentity != null)
{
// Ensure roles claim is an array of roles, even if there's only one role
var roles = claimsIdentity.FindAll("https://my-app.example.com/roles")
.Select(c => c.Value)
.ToList();

// Add roles to the claims identity
foreach (var role in roles)
{
claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, role));
}
}
}
};
});

builder.Services.AddAuthorization();
builder.Services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
Expand Down
1 change: 1 addition & 0 deletions SimpleWebAppReact.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
<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="RestSharp" Version="112.1.1-alpha.0.4" />
<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" />
Expand Down
25 changes: 14 additions & 11 deletions Startup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
/*using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
namespace SimpleWebAppReact;
/// <summary>
/// runs startup commands, builds front end, CORS
Expand Down Expand Up @@ -34,15 +36,16 @@ public void ConfigureServices(IServiceCollection services)
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.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://dev-2gowyyl3kin685ua.us.auth0.com/";
options.Audience = "http://localhost:5128";
options.TokenValidationParameters = new TokenValidationParameters
{
RoleClaimType = "https://my-app.example.com/roles" // Match the namespace in your token
};
});
services.AddAuthorization();
}
Expand Down Expand Up @@ -71,4 +74,4 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
endpoints.MapFallbackToFile("/index.html");
});
}
}
}*/

0 comments on commit 8e6b1b6

Please sign in to comment.