将变量从自定义过滤器传递给控制器​​操作方法

时间:2014-03-05 07:57:46

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

我有一个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);
        }
    }
}

现在如何在我的actionmethod中掌握该用户?

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

1 个答案:

答案 0 :(得分:2)

  

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

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/

相关问题