Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add i18n helpers #7

Merged
merged 2 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,31 @@ Blazor login page example:
}
```

# I18n helpers

Helpers to make it trivial to implement a client that pulls the language and culture info from the server.

```csharp
host.UseRequestLocalization(o => {
var cultures = ...;
o.AddSupportedCultures(cultures)
.AddSupportedUICultures(cultures)
.SetDefaultCulture(cultures[0]);
//insert before the final default provider (the AcceptLanguageHeaderRequestCultureProvider)
o.RequestCultureProviders.Insert(o.RequestCultureProviders.Count - 1, new OidcClaimsCultureProvider {Options = o});
});
```

Notice, this requires the server sets the culture info in the claims.
See below for example, or see `OidcClaimsCultureProviderHelper.AddClaims` for details.

You also need to copy it from the server given claims to the local claims. E.g. if using `StoreRemoteAuthInSchemeAsync`:

```csharp
yourContext.StoreRemoteAuthInSchemeAsync(..., (identity, remote)=>OidcClaimsCultureProviderHelper.CopyClaims(identity, remote))))
```


## Http helpers

### HttpClient for authentication code flow
Expand Down Expand Up @@ -400,3 +425,18 @@ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
o.ReturnStatusCodesOnAuthFailuresForApiCalls();
});
```

### I18n helper

Add OIDC standard claims for culture (`locale`) and the non-standard `ui-locales` for the ui-culture.

```csharp
public abstract class ApplyCultureToClaims(...) : OidcAccessGranterBase(...)
{
protected override Task<ImmutableArray<string>> SetClaimsAndGetScopes(...)
{
OidcClaimsCultureProviderHelper.AddClaimsFromCurrentCulture(identity);
return base.SetClaimsAndGetScopes(...);
}
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
#if NET
using Microsoft.AspNetCore.Localization;
using System.Security.Claims;

namespace Openiddict.Contrib.Client.I18nHelpers;

/// <summary>
/// Pull the <see cref="OpenIddictConstants.Claims.Locale"/> claim from the user and use that as the culture.
/// Also respects the non-standard "ui-locales" claim if present, in which case <see cref="OpenIddictConstants.Claims.Locale"/> is interpreted as the culture for formatting numbers, dates etc.
/// <example><code>
/// host.UseRequestLocalization(o =&gt; {
/// var cultures = ...;
/// o.AddSupportedCultures(cultures)
/// .AddSupportedUICultures(cultures)
/// .SetDefaultCulture(cultures[0]);
/// //insert before the final default provider (the AcceptLanguageHeaderRequestCultureProvider)
/// o.RequestCultureProviders.Insert(o.RequestCultureProviders.Count - 1, new OidcClaimsCultureProvider {Options = o});
/// });
/// </code></example>
/// </summary>
public class OidcClaimsCultureProvider : RequestCultureProvider
{
///<inheritdoc/>
public override Task<ProviderCultureResult?> DetermineProviderCultureResult(HttpContext httpContext) => Task.FromResult(GetCultureFromClaims(httpContext));

private static ProviderCultureResult? GetCultureFromClaims(HttpContext ctx)
{
var userCulture = ctx.User.GetClaim(OpenIddictConstants.Claims.Locale);
var userUiCulture = ctx.User.GetClaim(OpenIddictConstants.Parameters.UiLocales) ?? userCulture;
if (userUiCulture == null) goto noneFound;

return new(userCulture ?? userUiCulture, userUiCulture);
noneFound:
return null;
}

/// <summary>
/// Add appropriate claims for the given culture to the identity.
/// You probably want to use <see cref="CopyClaims"/> during login callback instead.
/// </summary>
/// <param name="identity">Identity to populate</param>
/// <param name="culture">Culture to use in BCP47 [RFC5646] format.</param>
public static void AddClaims(ClaimsIdentity identity, string? culture)
{
if (culture != null) identity.AddClaim(new Claim(OpenIddictConstants.Claims.Locale, culture.Replace('_', '-')));
}

/// <summary>
/// Add standard claims for the given culture to the identity, plus the custom "ui-locales".
/// You would usually use this if you are loading the culture info from db or similar.
/// You probably want to use <see cref="CopyClaims"/> during login callback instead.
/// </summary>
/// <param name="identity">Identity to populate</param>
/// <param name="culture">Culture to use in BCP47 [RFC5646] format.</param>
/// <param name="uiCulture">UI Culture to use in BCP47 [RFC5646] format. Ignored if same as culture.</param>
public static void AddClaims(ClaimsIdentity identity, string? culture, string? uiCulture)
{
AddClaims(identity, culture);
if (uiCulture != null && uiCulture != culture) identity.AddClaim(new(OpenIddictConstants.Parameters.UiLocales, uiCulture));
}

/// <summary>
/// Copy appropriate claims for the given culture to the identity from remote.
/// </summary>
/// <param name="identity">Identity to populate.</param>
/// <param name="remote">Remote claims.</param>
public static void CopyClaims(ClaimsIdentity identity, ClaimsPrincipal remote) => AddClaims(identity, remote.GetClaim(OpenIddictConstants.Claims.Locale), remote.GetClaim(OpenIddictConstants.Parameters.UiLocales));

}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System.Globalization;
using System.Security.Claims;

namespace Openiddict.Contrib.Server.I18nHelpers;

/// <summary>
/// Set the <see cref="OpenIddictConstants.Claims.Locale"/> claim from the user and use that as the culture.
/// <example><code>
/// host.UseRequestLocalization(o =&gt; {
/// var cultures = ...;
/// o.AddSupportedCultures(cultures)
/// .AddSupportedUICultures(cultures)
/// .SetDefaultCulture(cultures[0])
/// .RequestCultureProviders = new List&lt;IRequestCultureProvider&gt; {
/// new QueryStringRequestCultureProvider {Options = o},
/// new CookieRequestCultureProvider {Options = o},
/// new SoapClaimsCultureProvider {Options = o},
/// new OidcClaimsCultureProvider {Options = o},
/// new AcceptLanguageHeaderRequestCultureProvider {Options = o},
/// };
/// });
/// </code></example>
/// </summary>
public class OidcClaimsCultureProviderHelper
{
/// <summary>
/// Infer culture from current culture and add appropriate claims to the identity.
/// You would usually use this if you already have infrastructure in place to set the culture.
/// </summary>
/// <param name="identity">Identity to populate</param>
public static void AddClaimsFromCurrentCulture(ClaimsIdentity identity) => AddClaims(identity, CultureInfo.CurrentCulture.Name, CultureInfo.CurrentUICulture.Name);

/// <summary>
/// Add standard claims for the given culture to the identity.
/// You would usually use this if you are loading the culture info from db or similar.
/// </summary>
/// <param name="identity">Identity to populate</param>
/// <param name="culture">Culture to use in BCP47 [RFC5646] format.</param>
public static void AddClaims(ClaimsIdentity identity, string? culture)
{
if (culture != null) identity.AddClaim(new(OpenIddictConstants.Claims.Locale, culture));
}

/// <summary>
/// Add standard claims for the given culture to the identity, plus the custom "ui-locales".
/// You would usually use this if you are loading the culture info from db or similar.
/// </summary>
/// <param name="identity">Identity to populate</param>
/// <param name="culture">Culture to use in BCP47 [RFC5646] format.</param>
/// <param name="uiCulture">UI Culture to use in BCP47 [RFC5646] format. Ignored if same as culture.</param>
public static void AddClaims(ClaimsIdentity identity, string? culture, string? uiCulture)
{
AddClaims(identity, culture);
if (uiCulture != null && uiCulture != culture) identity.AddClaim(new(OpenIddictConstants.Parameters.UiLocales, uiCulture));
}
}
Loading