首页 > 解决方案 > 如何使用不记名令牌和 API 模块在 EmbedIO 中设置主体

问题描述

我正在使用承载令牌模块来保护 API 模块。

如何将 IHttpContext.User 属性设置为当前用户,以便我可以在我的控制器中访问它?

以下是 Web 服务器设置的相关部分:

WebServerEmbedded
    .WithCors()
    .WithBearerToken("/api", "0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9eyJjbGF", new MyAuthorizationServerProvider())
    .WithModule(webApiModule)

这是 MyAuthorizationServerProvider:

internal sealed class MyAuthorizationServerProvider: IAuthorizationServerProvider
{
    public async Task ValidateClientAuthentication(ValidateClientAuthenticationContext context)
    {
        var data = await context.HttpContext.GetRequestFormDataAsync().ConfigureAwait(false);

        if (data?.ContainsKey("grant_type") == true && data["grant_type"] == "password")
        {
            var username = data.ContainsKey("username") ? data["username"] : string.Empty;
            var password = data.ContainsKey("password") ? data["password"] : string.Empty;

            if (ValidateCredentials(username, password))
            {
                context.Validated(username);
            }
            else
            {
                context.Rejected();
            }
        }
        else
        {
            context.Rejected();
        }
    }

    public long GetExpirationDate() => DateTime.UtcNow.AddHours(12).Ticks;

    private static bool ValidateCredentials(string username, string password)
    {
        var user = BusinessLayer.CheckUserAndPassword(username, password);
        return user != null;
    }
}

谢谢。

标签: c#embedio

解决方案


我在 embedio-extras 存储库中发布了一个问题,并创建了一个拉取请求来解决它。如那里详述,升级到 Embedio (v3.3.3) 和 Embedio.BearerToken (v3.4.0) 会从承载令牌模块设置用户主体。

在控制器中 HttpContext.User 可用于访问主体。在调用之前,IAuthorizationServerProvider 实现中可能包含其他声明context.Validated(username);,例如:

context.Identity.AddClaim(new System.Security.Claims.Claim("Role", "Admin"));
context.Validated(username);

可以在控制器中像这样访问声明:

var principal = HttpContext?.User as ClaimsPrincipal;
if (null != principal)
{
    foreach (Claim claim in principal.Claims)
    {
        Log("Claim type: " + claim.Type + "; Claim value: " + claim.Value);
    }
}

推荐阅读