asp.net - 将变量从自定义过滤器传递到 Controller 操作方法

标签 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);
        }
    }
}

现在我如何在我的操作方法中找到该用户?

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

最佳答案

/////// Save the string username to the context so that I can acess it in the controler.

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;

// how do i get user here

var name = User.Identity.Name;

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

关于asp.net - 将变量从自定义过滤器传递到 Controller 操作方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22191803/

相关文章:

java - CoAP 服务器中的 EJB 处理?

c# - 将 2 个数据表合并为 1 个具有相同行数的数据表。

c# - Umbraco:在用户控件中列出子节点

c# - 为什么使用ASP.NET从另一个页面返回后无法激发Page_Load-ergo史诗般的尴尬:)

c# - 无法转换类型为 'System.Collections.Generic.List` 的对象 1[System.Decimal ]' to type ' System.IConvertible'

http - 202 Accepted 的反义词是什么?

C# 删除文件

javascript - 包括 unobtrusive-ajax 使所有脚本停止工作

javascript - 为什么 JQuery $.post 提交两次?

java - 将 BufferedWriter 与 HTTP 结合使用时出现 IOException