【问题标题】:Pass a variable from a Custom Filter to controller action method将自定义过滤器中的变量传递给控制器​​操作方法
【发布时间】:2014-04-07 03:50:03
【问题描述】:

我有一个 Web Api 项目。

我已经实现了一个自定义身份验证属性,如下所示:

public class TokenAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        // In auth web method you should implement functionality of authentication
        // so that client app could be able to get token
        if (actionContext.Request.RequestUri.AbsolutePath.Contains("api/auth/login"))
        {
            return;
        }

        // Receive token from the client. Here is the example when token is in header:
        var token = HttpContext.Current.Request.Headers["Token"];

        // Put your secret key into the configuration
        var secretKey = ConfigurationManager.AppSettings["JWTSecurityKey"];

        try
        {
            string jsonPayload = JWT.JsonWebToken.Decode(token, secretKey);

            int separatorIndex = jsonPayload.IndexOf(';');

            string userId = "";
            DateTime timeIssued = DateTime.MinValue;

            if (separatorIndex >= 0)
            {
                //userId = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(jsonPayload.Substring(0, separatorIndex)));
                userId = jsonPayload.Substring(0, separatorIndex);
                timeIssued = DateTime.Parse(jsonPayload.Substring(separatorIndex + 1));
            }

            short TokenTTL = 10;
            //try{
            //Int16.TryParse(ConfigurationManager.AppSettings["TokenTTL"],TokenTTL);
            //}catch(Exception e){           //}

            if ((DateTime.Now.Subtract(timeIssued).TotalMinutes >= TokenTTL))
            {
                throw new HttpResponseException(HttpStatusCode.Forbidden);
            }

            //Save user in context                
            var claims = new List<Claim>()
              {
                   new Claim(ClaimTypes.Name, userId)
              };
            var id = new ClaimsIdentity(claims, "Basic");
            var principal = new ClaimsPrincipal(new[] { id });

            actionContext.Request.GetRequestContext().Principal = principal;

        }
        catch (JWT.SignatureVerificationException)
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
    }
}

现在如何在我的操作方法中获取该用户?

[BasicHttpAuthorizeAttribute]
[httpGet]
public void Login()
{
 // how do i get user here
}

【问题讨论】:

    标签: asp.net asp.net-mvc http asp.net-web-api httpcontext


    【解决方案1】:

    /////// 将字符串用户名保存到上下文中,以便我可以访问 它在控制器中。

    var claims = new List<Claim>()
    {
        new Claim(ClaimTypes.Name, "john")
    };
    var id = new ClaimsIdentity(claims, "Basic");
    var principal = new ClaimsPrincipal(new[] { id });
    actionContext.Request.GetRequestContext().Principal = principal;
    

    //我如何在这里获得用户

    var name = User.Identity.Name;
    

    顺便说一句,使用身份验证过滤器而不是授权过滤器来执行身份验证。请参阅我的博文 - http://lbadri.wordpress.com/2014/02/13/basic-authentication-with-asp-net-web-api-using-authentication-filter/

    【讨论】:

    • 我得到了错误:在最后一行,.GetRequestContext() 带有红色下划线。 (不包含“getrequestcontex”的定义`
    • 我正在使用它来验证每个请求的 JWT 令牌。身份验证过滤器是否仍然适用于此?
    • 将此指令添加到 TokenAuthenticationAttribute 类 - using System.Net.Http;
    • 您应该使用身份验证过滤器来验证各种凭据。
    • 另外我怎样才能跳过身份验证过程。例如,当我去 auth/login 时,我不希望它进行身份验证
    猜你喜欢
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多