asp.net - 如何在其他 Controller 中使用授权用户名

标签 asp.net asp.net-mvc asp.net-web-api

使用基本身份验证和 asp.net Web-Api(其中 JSON Get/Post 到我的 API),我需要检查用户名/密码是否存在于成员资格表中。下面的代码的作用是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

namespace MvcApplication4.Filter
{
    public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.Request.Headers.Authorization == null)
            {
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }
            else
            {
                string authToken = actionContext.Request.Headers.Authorization.Parameter;
                string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
                string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
                string password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);

                if (Membership.Provider.ValidateUser(username, password))
                {
                    // User exists in the membership table
                }
                else
                {
                    // User doesn't exist - so return Unathorized
                    actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
                }
            }
        }
    }
}

我需要引用其他 Controller 中的用户名,以确保该用户名也存在于查找表中,该表说明允许用户查询哪些汽车。我的数据库中有一个表和一个关联的类:

public class ApiMembers
    {
        public int id { get; set; }
        public string UserName { get; set; }
        public int car_id { get; set; }
    }


 [BasicAuthentication]
        public IEnumerable<Cars> GetCars(long id)
        {
            var auth = dba.ApiMembers.Select(a => a.car_id == id && a.UserName=***AuthorisedUserName***).FirstOrDefault();
            if (auth == null || !auth.Any())
                 {
                        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
                 }
            else
            {
                // User exists in table, so give them info on car
            }

我的问题是,无需再次读取 HTTP header ,如何将 UserName 放入 AuthorizedUserName 部分?有没有办法在 BasicAuthentication 过滤器中“登录”用户,或者可以使用 session 变量,就像在 Web 表单中一样?或者是否有更好的方法来了解谁已在其他 Controller 中进行了身份验证?

最佳答案

您可以设置当前主体:

if (Membership.Provider.ValidateUser(username, password))
{
    // User exists in the membership table
    var identity = new GenericIdentity(username);
    Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
}

现在在你的 ApiController 中你可以使用 User属性来访问当前连接的用户名(请注意,此属性是在 ASP.NET MVC 4 RC 中添加的 - 在以前的版本中,您可以使用 Request.GetPrincipal 扩展方法)。

[BasicAuthentication]
public HttpResponseMessage Get()
{
    string username = User.Identity.Name;

    ...
}

关于asp.net - 如何在其他 Controller 中使用授权用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11135473/

相关文章:

c# - 具有两个 GET 操作的 WebApi Controller

c# - 查询字符串?&空参数Web API

c# - 读取用户 session 时出现 NULL 引用异常(反射)

asp.net - itextsharp 向所有页面添加 1 个页面模板

asp.net-mvc - 如何从 ActionFilter 中跳过操作执行?

asp.net - AllowAnonymous 是否覆盖 AuthorizeAttribute

c# - 如何使用自定义身份验证和内存托管进行 ASP.NET Web API 集成测试

c# - 更新 asp.net 中的 web.config 文件

.net - 如何告诉 ASP.NET MVC 在库中查找 Controller ?

c# - 通过提交按钮传递值?