【问题标题】:Web API authentication response propertiesWeb API 身份验证响应属性
【发布时间】:2014-10-27 13:22:02
【问题描述】:

我正在使用 ASP.NET Web API 开发 Web 服务。我正在使用 ASP.NET Identity 进行身份验证和令牌生成。我需要在令牌响应 json 中返回一个扩展属性。到目前为止,我能够返回一个扩展字符串属性,在该属性中我发送一个通过将自定义类对象序列化为 json 获得的 json 字符串。以下是我的身份验证提供程序代码:

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        await Task.Run(() =>
        {
            context.Validated();
        });            
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        await Task.Run(() =>
        {
            var loginResponse = new AccountManager().Login(context.UserName, context.Password);

            if (loginResponse == null)
            {
                context.SetError("invalid_grant", Resources.Messages.InvalidGrant);
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            IDictionary<string, string> data = new Dictionary<string, string>
            {
                { "userData", JsonConvert.SerializeObject(loginResponse) }
            };
            AuthenticationProperties properties = new AuthenticationProperties(data);

            Microsoft.Owin.Security.AuthenticationTicket ticket = new Microsoft.Owin.Security.AuthenticationTicket(identity, properties);
            context.Validated(ticket);
        });            
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }

        return Task.FromResult<object>(null);
    }
}

现在在我的回复中,我有一个属性,例如"userData" : "&lt;Json String&gt;" 而我想将一个 json 对象(不是 json 字符串)分配给 userData。有可能吗?

【问题讨论】:

  • 试图准确地理解你在做什么,有没有理由你不能随心所欲地构建你的对象,然后使用 stringify 方法将其转换为 JSON 字符串?
  • 添加了类似问题的答案stackoverflow.com/questions/40841971/…

标签: c# json asp.net-web-api asp.net-identity


【解决方案1】:

我不建议将 JSON 对象放在票证属性中,这会大大增加令牌大小,并且您会在每个请求中传输此令牌。 如果您在获得访问令牌后定义受保护的独立端点来执行此任务,也许会更好。成功登录后您将发出额外的 Get 请求,但您将保持令牌大小最小。

【讨论】:

  • 只想再确认一件事,那就是在身份中添加声明有什么用?例如identity.AddClaim(new Claim("sub", context.UserName));
  • 在 AuthenticationProperties 中添加 JSON 对象时,不会增加令牌的大小,而只是向响应对象添加另一个属性。令牌仅包含声明,而不包含属性。所以不,您不会在每个请求上提交属性,这样做完全没问题。
猜你喜欢
  • 1970-01-01
  • 2017-10-22
  • 2014-01-28
  • 2012-06-16
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2016-11-13
相关资源
最近更新 更多