0

我的另一个问题,耶!

好的,所以我有这个代码:

public class TokenMessageHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var token = request.Headers.GetValues("Authorization-Token").FirstOrDefault();
        if (String.IsNullOrEmpty(token))
            return Task<HttpResponseMessage>.Factory.StartNew(() =>
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Missing Authorization-Token")
                };
            });

        try
        {
            var user = UserRepository.GetUsers().FirstOrDefault(x => x.UserName == RSAClass.Decrypt(token));
            if (user == null)
                return Task<HttpResponseMessage>.Factory.StartNew(() =>
                {
                    return new HttpResponseMessage(HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent("Unauthorized User")
                    };
                });

            var identity = new GenericIdentity(user.UserName);
            var principal = new GenericPrincipal(identity, null);

            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
                HttpContext.Current.User = principal;
        }
        catch (RSAClass.RSAException)
        {
            return Task<HttpResponseMessage>.Factory.StartNew(() =>
            {
                return new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("Error encountered while attempting to process authorization token")
                };
            });
        }

        return base.SendAsync(request, cancellationToken);
    }
}

它工作得很好。如果我像这样使用我的 jQuery 调用 api:

function GetAllCategories() {
    var credentials = '@ViewBag.encrypted';

    $.ajax({
        url: "http://localhost:18904/api/Categories",
        type: "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization-Token", credentials);
        },
        success: function (data) {
            $.each(data, function (i, category) {
                var row = '<tr><td>' + category.DisplayName + '</td><td>' + category.DateCreated + '</td><td>' + category.AssetCount + '</td><td>' + category.CategoryCount + '</td></tr>';
                $('#categories').append(row);
            });
        },
        error: function () {
            alert('error');
        }
    });
}

我得到了一个很好的类别列表。高手。现在如您所见,我正在设置 CurrentPrincipal 和 Current.User。在我的 CategoriesController 中,我可以访问我的 User.Identity,这很棒。

我的问题是:我有自己的个人资料,其中存储了许多其他信息,因此通用 MembershipUser 是不够的。那么如何设置我的个人资料以便它持续存在。例如,我想设置一些将保留在 MessageHandler 中的内容,例如设置 HttpContext.Current.User 或 Thread.CurrentPrincipal。

谁能帮我一把?

干杯,

/r3plica

4

1 回答 1

0

我做了类似的事情,但我实现了自己的 IIdentity 而不是 GenericIdentity。

var identity = new ApiIdentity(user);

public class ApiIdentity : IIdentity
{
    public ApiIdentity(UserModel user)
    {
        User = user;
    }

    public UserModel User { get; set; }

    #region IIdentity Members

    public string Name
    {
        get { return User.UserId.ToString(); }
    }

    public string AuthenticationType
    {
        get { return "Basic"; }
    }

    public bool IsAuthenticated
    {
        get { return true; }
    }

    #endregion
}

然后在我的 BaseApiController 中,我可以访问身份并像 Identity.User.xxx 一样使用它:

    public ApiIdentity Identity
    {
        get { return HttpContext.Current.User.Identity as ApiIdentity; }
    }
于 2014-01-24T18:25:27.817 回答