Friday, November 29, 2024

Blazor Web App: Adding Custom Claims to Current User

I recently had a requirement where I want to add Custom Claims to the current user in a Blazor Web Application. I used IClaimsTransformation, but it doesn't work with Blazor. Instead, the correct option for Blazor is to implement a custom AuthenticationStateProvider.

public class ApplicationAuthenticationStateProvider : AuthenticationStateProvider
{
    private readonly AuthenticationStateProvider _authenticationStateProvider;
    private readonly IUserService _userService;

    public ApplicationAuthenticationStateProvider(AuthenticationStateProvider AuthenticationStateProvider, IUserService userService)
    {
        _authenticationStateProvider = AuthenticationStateProvider;
        _userService = userService;
    }

    public override async Task<AuthenticationState> GetAuthenticationStateAsync()
    {
        AuthenticationState authenticationState =  await _authenticationStateProvider.GetAuthenticationStateAsync();
        if (authenticationState.User.Identity?.IsAuthenticated != true)
        {
            return authenticationState;
        }

        // Check if user already has the UserId claim
        if (authenticationState.User.HasClaim(x => x.Type == ApplicationClaimTypes.UserId))
        {
            return authenticationState;
        }

        // TODO: Get the user from the database using current claims and IUserService
        string applicationUserId = "someUserId";

        ClaimsIdentity claimsIdentity = new ClaimsIdentity();
        claimsIdentity.AddClaim(new Claim(ApplicationClaimTypes.UserId, applicationUserId));

        authenticationState.User.AddIdentity(claimsIdentity);

        return authenticationState;
    }
}

Register ApplicationAuthenticationStateProvider,

builder.Services.AddScoped<ApplicationAuthenticationStateProvider>();

Use,

// This is some service where you want to use authenticationState
public class BlazorIdentityService : IIdentityService
{
    private readonly ApplicationAuthenticationStateProvider _applicationAuthenticationStateProvider;

    public BlazorIdentityService(ApplicationAuthenticationStateProvider applicationAuthenticationStateProvider)
    {
        _applicationAuthenticationStateProvider = applicationAuthenticationStateProvider;
    }

    public async Task<string> GetCurrentUserId()
    {
        AuthenticationState authenticationState =  await _applicationAuthenticationStateProvider?.GetAuthenticationStateAsync();

        return authenticationState.User?.Claims?.SingleOrDefault(x => x.Type == ApplicationClaimTypes.UserId)?.Value;
    }
}

Hope this helps.

Happy Coding.

Regards,
Jaliya

Tuesday, November 26, 2024

Azure APIM Backends with OpenAPI Specifications: Importance of operationId

I recently faced an issue in one of the APIs where as part of importing OpenAPI to Azure APIM, it started throwing an error: "(ValidationError) Operation with the same method and URL template already exists".

Let's have a look at a Minimal Reproducible Example (MRE).

Say I have the following ASP.NET Core API controller that is getting exposed in OpenAPI Spec.
[Route("api/some/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/long-resources")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return ["value1""value2"];
    }

    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }
}
When I import this to APIM, it's getting imported.

Note the operationId
OpenAPI Specification
Since the code hasn't explicitly specified an operationId, APIM is generating the operationId by following a convention (see Normalization rules for operationId).

Now let's remove the first endpoint and try to import again.
[Route("api/some/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/long-resources")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }
}
This time I am getting the error.
(ValidationError) Operation with the same method and URL template already exists
Since we no longer have multiple operations, now for the operationId no de-duplication suffix will be used, but the newly generated operationId is the same operationId that was previously used for"GET: /api/some/very/.../long-resources" endpoint.

We can fix this by adding operationId in the code, as follows.
[Route("api/some/very/very/very/very/very/very/very/very/very/very/very/very/very/very/very/long-resources")]
[ApiController]
public class ValuesController : ControllerBase
{
    [HttpGet("{id}", Name = "GetValueById")]
    public string Get(int id)
    {
        return "value";
    }
}
Explicit operationId
So as a practice, we should always consider explicitly specifying operationId in our code rather than letting APIM auto-generate one.And this is going to be very important if you are using APIOps and has custom APIM policy overrides for operations. Because the policies are maintained by operationId and if operationId generation convention is changed for some reason, your APIOps deployments will fail.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, November 14, 2024

Blazor Web App: Authentication Redirect URI is not HTTPS

.NET 9 is finally out and I was playing around with Blazor. I was setting up Authentication in a .NET 9 Blazor Web App. The authentication is configured with AzureAD, and locally everything was working fine. The application was running on HTTPS and the redirect_uri was HTTPS too.  

When the application was deployed to Azure, the Authentication was failing, because the redirect_uri was HTTP.  In Azure AD App Registration I configured it with HTTPS (HTTP is allowed only when using localhost). The application was running inside a Linux Container in an Azure Web App.

In order for redirect_uri to be HTTPS, I had to do the following:

1. Enable UseForwardedHeaders

WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
// Other service registrations

WebApplication app = builder.Build();

// Note: Forwarded Headers Middleware should run before other middleware. 
// This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing. 
// Forwarded Headers Middleware can run after diagnostics and error handling, but it MUST BE RUN before calling UseHsts
app.UseForwardedHeaders();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error"createScopeForErrorstrue);
    app.UseHsts();
}

app.UseHttpsRedirection();
// Other middleware

app.Run();

2. Add the following app setting in Azure (More: Forward the scheme for Linux and non-IIS reverse proxies)

{
  "name""ASPNETCORE_FORWARDEDHEADERS_ENABLED",
  "value""true",
  "slotSetting"false
}

And that did it.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, November 6, 2024

Azure APIM: Policy Expression to Read application/x-www-form-urlencoded Request Data

Recently I had a requirement where a particular Client sends some request data as application/x-www-form-urlencoded and needed to get those moved to the request header before it gets forwarded to the Backend.

In this post, let's see how we can read request data sent via application/x-www-form-urlencoded.

If we have a look at .NET Framework types allowed in policy expressions, we have access to System.Net.WebUtility.

So we can make use of that as follows:
<policies>
    <inbound>
        <!--Extract URL Encoded Form Data (if any)-->
        <set-variable name="serializedFormData" value="@{
            var formData = new System.Collections.Generic.Dictionary<String, String>();
            if(context.Request.Headers.GetValueOrDefault("Content-Type", "") != "application/x-www-form-urlencoded")
            {
                return JsonConvert.SerializeObject(formData);
            }

            string encodedBody = context.Request.Body.As<String>(preserveContent: true);
            string decodedBody = System.Net.WebUtility.UrlDecode(encodedBody);
            foreach (string key in decodedBody.Split('&'))
            {
                string[] keyValue = key.Split('=');
                formData.Add(keyValue[0], keyValue[1]);
            }

            return JsonConvert.SerializeObject(formData);
        }" />
        <!--Check if the interested headers are sent in the form data-->
        <set-variable name="isRequiredHeadersSentInFormData" value="@{
            string serializedFormData = context.Variables.GetValueOrDefault<String>("serializedFormData");
            System.Collections.Generic.Dictionary<String, String> formData = 
                JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<String, String>>(serializedFormData);

             return formData.ContainsKey("key1") && formData.ContainsKey("key2");
        }" />
        <!--Set the headers from the form data if present-->
        <choose>
            <when condition="@(context.Variables.GetValueOrDefault<bool>("isRequiredHeadersSentInFormData"))">
                <set-header name="x-key1" exists-action="override">
                    <value>@{
                        string serializedFormData = context.Variables.GetValueOrDefault<String>("serializedFormData");
                        System.Collections.Generic.Dictionary<String, String> formData = 
                            JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<String, String>>(serializedFormData);

                        return formData["key1"];
                    }</value>
                </set-header>
                <set-header name="x-key2" exists-action="override">
                    <value>@{
                        string serializedFormData = context.Variables.GetValueOrDefault<String>("serializedFormData");
                        System.Collections.Generic.Dictionary<String, String> formData = 
                            JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<String, String>>(serializedFormData);

                        return formData["key2"];
                    }</value>
                </set-header>
            </when>
        </choose>
        ...
    </inbound>
    ...
</policies>
And now we test with trace, we can see the request is correctly being transformed.
Trace
Hope this helps.

Happy Coding.

Regards,
Jaliya