zoukankan      html  css  js  c++  java
  • asp.net mvc api auth

    一、登录

    /// <summary>
    /// 获取令牌
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <param name="password">密码</param>
    /// <returns></returns>
    [HttpGet]
    public object Login(string userName, string password)
    {

    if(验证没通过)
        return Json("用户名或密码错误");
    FormsAuthenticationTicket token = new FormsAuthenticationTicket(0, userName, DateTime.Now,DateTime.Now.AddHours(1), true,userName,
    FormsAuthentication.FormsCookiePath);
    //返回登录结果、用户信息、用户验证票据信息
    var Token = FormsAuthentication.Encrypt(token);
    //将身份信息保存在Cache中,一小时之内有访问有效
    HttpRuntime.Cache.Insert(userName, Token, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1,0,0), System.Web.Caching.CacheItemPriority.Default, null);

    return Json(new { token = Token });
    }

    二、api auth

    using System.Linq;
    using System.Web;
    using System.Web.Http;
    using System.Web.Http.Controllers;
    using System.Web.Security;

    public class ApiAuthAttribute : AuthorizeAttribute// ActionFilterAttribute
    {
    public override void OnAuthorization(HttpActionContext actionContext)
    {
    var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
    var token = content.Request.QueryString["Token"];
    if (!string.IsNullOrEmpty(token))
    {
    //解密用户ticket,并校验用户名密码是否匹配
    if (ValidateTicket(token))
    {
    base.IsAuthorized(actionContext);
    }
    else
    HandleUnauthorizedRequest(actionContext);

    }
    else
    HandleUnauthorizedRequest(actionContext);
    }
    private bool ValidateTicket(string encryptToken)
    {
    //解密Ticket
    var userName = FormsAuthentication.Decrypt(encryptToken).UserData;

    var token = HttpRuntime.Cache.Get(userName)?.ToString();

    if (token == null)
    {
    return false;
    }


    //对比session中的令牌
    if (token == encryptToken)
    {
    return true;
    }

    return false;

    }
    }

    三、在需要验证的地方添加[ApiAuth]

  • 相关阅读:
    PHP学习—了解篇2
    PHP学习—了解篇
    德国山寨史
    Network client/server
    Linux (二) vi
    I2C 总线协议
    Verilog (二) multiplexer and decoder
    有限状态机HDL模板
    "德意志之歌"的历史
    【转】java与.net比较学习系列(3) 基本数据类型和类型转换
  • 原文地址:https://www.cnblogs.com/catzhou/p/5972697.html
Copyright © 2011-2022 走看看