Web Api User.Identity.Name

时间:2013-05-10 18:17:57

标签: asp.net-web-api

我的另一个问题,耶!

好的,我有这段代码:

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

1 个答案:

答案 0 :(得分: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; }
    }