ASP.NET Web API 2自定义授权和授权属性

时间:2019-12-19 08:37:09

标签: c# asp.net authentication asp.net-web-api forms-authentication

我创建了一个Google Chrome扩展程序,并计划与ASP.NET Wep API 2服务进行通信。 Web服务将创建加密的FormsAuthenticationTicket,并在第一次的Login / SignIn响应中发送它。通过检查Request Cookie来控制验证用户是否被授权。

项目通过GetEncryptedTicket(int UserID)函数创建票证。

如何控制和使用服务功能上方的[Authorize]属性?我知道oAuth 2.0可能是实现它的更好选择,但我想使用以下函数来创建票证。

public static string GetEncryptedTicket(int UserID)
{
    DateTime now = DateTime.UtcNow.ToLocalTime();

    var ticket = new FormsAuthenticationTicket(
        1,
        "TICKET_NAME",
        now,
        now.Add(FormsAuthentication.Timeout),
        true,
        UserID.ToString(),
        FormsAuthentication.FormsCookiePath
        );

    string encryptedTicket = FormsAuthentication.Encrypt(ticket);

    return encryptedTicket;
}

1 个答案:

答案 0 :(得分:0)

使用操作过滤器来验证令牌,如下所示 公共类BasicAuthenticationAttribute:ActionFilterAttribute     {

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            if (actionContext.Headers.GetValues("UserToken").FirstOrDefault() == null)
            {

                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
                {
                    ReasonPhrase = "Http request doesnot have the UserToken header"
                };
            }
            else
            {
                string username = string.Empty, password = string.Empty;

                var userToken = actionContext.Request.Headers.GetValues("UserToken").FirstOrDefault();
                var token = FormsAuthentication.Decrypt(userToken);

                if (token.Expired)
                {
                    actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
                    {
                        ReasonPhrase = "Invalid User Token"
                    };

                }


            }

        }

        catch (Exception ex)
        {

            actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError)
            {
                ReasonPhrase = ex.Message
            };

        }


    }       

} 

并使用[BasicAuthentication]属性验证令牌并允许访问