Webapi 2.0如何在访问令牌过期时实现刷新JWT令牌

时间:2018-01-18 11:39:35

标签: asp.net c#-4.0 webforms asp.net-web-api2 dotnet-httpclient

我是Web API实现的新手,我创建了一个Web API服务,用于ASP.net web form个应用程序以及一些使用HttpClient对象的独立应用程序(C#Console / Windows应用程序)

我已经在web api中实现了一个带有过期时间限制的基本JWT访问令牌身份验证,这种身份验证技术正常工作,直到令牌未过期,当令牌过期时,web api不接受请求,因为令牌已过期!根据身份验证实现很好,但我想在web api中实现刷新令牌逻辑,因此令牌可以续订/引用,客户端应该能够使用web api资源。

我google了很多但无法找到刷新令牌逻辑的正确实现。如果任何人有正确的方法来处理过期的访问令牌,请帮助我。

以下是我在asp.net应用程序中使用web api时所遵循的步骤。

  1. 在ASP.net Web表单登录页面中,我调用了Web API“TokenController”,该控制器采用了两个参数loginID和password,并返回我存储在会话对象中的JWT令牌。

  2. 现在,每当我的客户端应用程序需要使用时,web api资源必须在使用httpclient调用web api时在请求标头中发送访问令牌。

  3. 但是当令牌过期客户端无法使用web api资源时,他必须再次登录并续订令牌!这个我不想要,用户不应该提示再次登录,因为应用程序会话时间尚未过去。

  4. 如何在不强制用户再次登录的情况下刷新令牌。

    如果我给出的JWT访问令牌实现逻辑不合适或不正确,请告诉我正确的方法。

    以下是代码。

    的WebAPI

    AuthHandler.cs

      public class AuthHandler : DelegatingHandler
        {
    
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
                    CancellationToken cancellationToken)
        {
            HttpResponseMessage errorResponse = null;           
            try
            {
                IEnumerable<string> authHeaderValues;
                request.Headers.TryGetValues("Authorization", out authHeaderValues);
    
                if (authHeaderValues == null)
                    return base.SendAsync(request, cancellationToken);
    
                var requestToken = authHeaderValues.ElementAt(0);
    
                var token = "";
    
                if (requestToken.StartsWith("Bearer ", StringComparison.CurrentCultureIgnoreCase))
                {
                    token = requestToken.Substring("Bearer ".Length);
                }
    
                var secret = "w$e$#*az";
    
                ClaimsPrincipal cp = ValidateToken(token, secret, true);
    
    
                Thread.CurrentPrincipal = cp;
    
                if (HttpContext.Current != null)
                {
                    Thread.CurrentPrincipal = cp;
                    HttpContext.Current.User = cp;
                }
            }
            catch (SignatureVerificationException ex)
            {
                errorResponse = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
            }
            catch (Exception ex)
            {
                errorResponse = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
    
    
            return errorResponse != null
                ? Task.FromResult(errorResponse)
                : base.SendAsync(request, cancellationToken);
        }
    
        private static ClaimsPrincipal ValidateToken(string token, string secret, bool checkExpiration)
        {
            var jsonSerializer = new JavaScriptSerializer();
            string payloadJson = string.Empty;
    
            try
            {
                payloadJson = JsonWebToken.Decode(token, secret);
            }
            catch (Exception)
            {
                throw new SignatureVerificationException("Unauthorized access!");
            }
    
            var payloadData = jsonSerializer.Deserialize<Dictionary<string, object>>(payloadJson);
    
    
            object exp;
            if (payloadData != null && (checkExpiration && payloadData.TryGetValue("exp", out exp)))
            {
                var validTo = AuthFactory.FromUnixTime(long.Parse(exp.ToString()));
                if (DateTime.Compare(validTo, DateTime.UtcNow) <= 0)
                {
                    throw new SignatureVerificationException("Token is expired!");
                }
            }
    
            var clmsIdentity = new ClaimsIdentity("Federation", ClaimTypes.Name, ClaimTypes.Role);
    
            var claims = new List<Claim>();
    
            if (payloadData != null)
                foreach (var pair in payloadData)
                {
                    var claimType = pair.Key;
    
                    var source = pair.Value as ArrayList;
    
                    if (source != null)
                    {
                        claims.AddRange(from object item in source
                                        select new Claim(claimType, item.ToString(), ClaimValueTypes.String));
    
                        continue;
                    }
    
                    switch (pair.Key.ToUpper())
                    {
                        case "USERNAME":
                            claims.Add(new Claim(ClaimTypes.Name, pair.Value.ToString(), ClaimValueTypes.String));
                            break;
                        case "EMAILID":
                            claims.Add(new Claim(ClaimTypes.Email, pair.Value.ToString(), ClaimValueTypes.Email));
                            break;
                        case "USERID":
                            claims.Add(new Claim(ClaimTypes.UserData, pair.Value.ToString(), ClaimValueTypes.Integer));
                            break;
                        default:
                            claims.Add(new Claim(claimType, pair.Value.ToString(), ClaimValueTypes.String));
                            break;
                    }
                }
    
            clmsIdentity.AddClaims(claims);
    
            ClaimsPrincipal cp = new ClaimsPrincipal(clmsIdentity);
    
            return cp;
        }
    
    
    }
    

    AuthFactory.cs

    public static class AuthFactory
    {
    internal static DateTime FromUnixTime(double unixTime)
    {
        var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return epoch.AddSeconds(unixTime);
    }
    
    
    internal static string CreateToken(User user, string loginID, out double issuedAt, out double expiryAt)
    {
    
        var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        expiryAt = Math.Round((DateTime.UtcNow.AddMinutes(TokenLifeDuration) - unixEpoch).TotalSeconds);
        issuedAt = Math.Round((DateTime.UtcNow - unixEpoch).TotalSeconds);
    
        var payload = new Dictionary<string, object>
            {
                {enmUserIdentity.UserName.ToString(), user.Name},
                {enmUserIdentity.EmailID.ToString(), user.Email},
                {enmUserIdentity.UserID.ToString(), user.UserID},
                {enmUserIdentity.LoginID.ToString(), loginID}
                ,{"iat", issuedAt}
                ,{"exp", expiryAt}
            };
    
        var secret = "w$e$#*az";
    
        var token = JsonWebToken.Encode(payload, secret, JwtHashAlgorithm.HS256);
    
        return token;
    }
    
    public static int TokenLifeDuration
    {
        get
        {
            int tokenLifeDuration = 20; // in minuets
            return tokenLifeDuration;
        }
    }
    
    internal static string CreateMasterToken(int userID, string loginID)
    {
    
        var payload = new Dictionary<string, object>
            {
                {enmUserIdentity.LoginID.ToString(), loginID},
                {enmUserIdentity.UserID.ToString(), userID},
                {"instanceid", DateTime.Now.ToFileTime()}
            };
    
        var secret = "w$e$#*az";
    
        var token = JsonWebToken.Encode(payload, secret, JwtHashAlgorithm.HS256);
    
        return token;
    }
    

    }

    WebApiConfig.cs

    public static class WebApiConfig
    {
    
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
            config.Formatters.Remove(config.Formatters.XmlFormatter);
    
            config.MessageHandlers.Add(new AuthHandler());
        }
    }
    

    TokenController .cs

    public class TokenController : ApiController
    {
        [AllowAnonymous]
        [Route("signin")]
        [HttpPost]
        public HttpResponseMessage Login(Login model)
        {
            HttpResponseMessage response = null;
            DataTable dtblLogin = null;
            double issuedAt;
            double expiryAt;
    
            if (ModelState.IsValid)
            {
                dtblLogin = LoginManager.GetUserLoginDetails(model.LoginID, model.Password, true);
    
                if (dtblLogin == null || dtblLogin.Rows.Count == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.NotFound);
                }
                else
                {
                    User loggedInUser = new User();
                    loggedInUser.UserID = Convert.ToInt32(dtblLogin.Rows[0]["UserID"]);
                    loggedInUser.Email = Convert.ToString(dtblLogin.Rows[0]["UserEmailID"]);
                    loggedInUser.Name = Convert.ToString(dtblLogin.Rows[0]["LastName"]) + " " + Convert.ToString(dtblLogin.Rows[0]["FirstName"]);
    
                    string token = AuthFactory.CreateToken(loggedInUser, model.LoginID, out issuedAt, out expiryAt);
                    loggedInUser.Token = token;
    
                    response = Request.CreateResponse(loggedInUser);
    
                }
            }
            else
            {
                response = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            return response;
        }
    
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    
    }
    

    PremiumCalculatorController.cs

    PremiumCalculatorController : ApiController
    {
        [HttpPost]
        public IHttpActionResult CalculatAnnualPremium(PremiumFactorInfo premiumFactDetails)
        {
          PremiumInfo result;
          result = AnnualPremium.GetPremium(premiumFactDetails);
          return Ok(result);
        }
    }
    

    网络表单应用

    Login.aspx.cs

    public class Login
    {
        protected void imgbtnLogin_Click(object sender, System.EventArgs s)
        {
    
        UserInfo loggedinUser = LoginManager.ValidateUser(txtUserID.text.trim(), txtPassword.text);
    
        if (loggedinUser != null)
        {
    
            byte[] password = LoginManager.EncryptPassword(txtPassword.text);
    
            APIToken tokenInfo = ApiLoginManager.Login(txtUserID.text.trim(), password);
    
            loggedinUser.AccessToken = tokenInfo.Token;
    
            Session.Add("LoggedInUser", loggedinUser);
    
            Response.Redirect("Home.aspx");
    
        }
        else
        {
            msg.Show("Logn ID or Password is invalid.");
        }
    
    
        }
    }
    

    ApiLoginManager.cs

    public class ApiLoginManager
    {
        public UserDetails Login(string userName, byte[] password)
        {
            APIToken result = null;
            UserLogin objLoginInfo;
            string webAPIBaseURL = "http://localhost/polwebapiService/"
            try
            {
                using (var client = new HttpClient())
                {
                    result = new UserDetails();
                    client.BaseAddress = new Uri(webAPIBaseURL);
                    objLoginInfo = new UserLogin { LoginID = userName, Password = password };
    
                    var response = client.PostAsJsonAsync("api/token/Login", objLoginInfo);
    
                    if (response.Result.IsSuccessStatusCode)
                    {
                        string jsonResponce = response.Result.Content.ReadAsStringAsync().Result;
                        result = JsonConvert.DeserializeObject<APIToken>(jsonResponce);
                    }
    
                    response = null;
                }
    
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
    
        }
    
    }
    

    AnnualPremiumCalculator.aspx.cs

    public class AnnualPremiumCalculator
    {
        protected void imgbtnCalculatePremium_Click(object sender, System.EventArgs s)
        { 
           string token = ((UserInfo)Session["LoggedInUser"]).AccessToken;
           PremiumFactors premiumFacts = CollectUserInputPremiumFactors();
           PremiumInfo premiumDet = CalculatePremium(premiumFacts, token);
           txtAnnulPremium.text = premiumDet.Premium;
           //other details so on 
        }
    
        public PremiumInfo CalculatePremium(PremiumFactors premiumFacts, string accessToken)
        {
            PremiumInfo result = null;
            string webAPIBaseURL = "http://localhost/polwebapiService/";
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(webAPIBaseURL);
    
                    StringContent content = new StringContent(JsonConvert.SerializeObject(premiumFacts), Encoding.UTF8, "application/json");
    
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
    
                    var response = client.PostAsync("api/calculators/PremiumCalculator", content);
    
                    if (response.Result.IsSuccessStatusCode)
                    {
                        string jsonResponce = response.Result.Content.ReadAsStringAsync().Result;
                        result = JsonConvert.DeserializeObject<PremiumInfo>(jsonResponce);
                    }
    
                    response = null;
    
                }
    
                return result;
            }
            finally
            {
    
            }
    
        }
    
    }
    

    上面是一个示例代码来说明问题,它可能有一些错字。

2 个答案:

答案 0 :(得分:3)

这可以使用单独的持久刷新令牌来完成。 http://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web-token/

的精彩教程

答案 1 :(得分:3)

我有一些评论:

  1. 访问令牌旨在由客户端保存,而不是保存在服务器上的会话中。刷新令牌的计数相同。原因是,通常没有会话。智能客户端可以在没有会话的情况下处理令牌,MVC网站可以使用cookie并且API不知道会话。它不是被禁止的,但是你需要再次担心会话过期,并且当你重新启动服务器时所有用户都必须再次登录。

  2. 如果您想实施OAuth,请阅读specification。在那里,您将找到实现刷新令牌所需的一切。

  3. 在TokenController中,您处理登录。在那里你也应该检查other conditions

    • grant_type =密码
    • Content-Type必须是“application / x-www-form-urlencoded”
    • 只有通过安全线路(https)发送才能处理请求。
  4. 获取access_token时,仅当请求了refresh_token时,您应该在access_token中包含refresh_token

  5. 您不需要client applications(grant_type = client_credentials)的刷新令牌,因为那些使用clientid / secret来获取访问令牌。扩展TokenController以允许client_credentials流。请注意:刷新令牌仅适用于用户,只有在可以保密的情况下才能使用。刷新令牌非常强大,因此请小心处理。

  6. 为了refresh an access token,您需要将刷新令牌发送到端点。在您的情况下,您可以扩展TokenController以允许refresh_token请求。你需要检查:

    • grant_type = refresh_token
    • Content-Type必须是“application / x-www-form-urlencoded”
  7. 刷新令牌有几种情况,您也可以将它们组合在一起:

    • 将刷新令牌保存在数据库中。每次使用刷新令牌时,您都可以将其从数据库中删除,然后保存新的刷新令牌,该令牌也会在新的access_token中返回。
    • 将刷新令牌设置为更长的生命周期,并且在刷新访问令牌时不刷新它。在这种情况下,返回的access_token不包含新的刷新令牌。这样你就需要在refresh_token到期后再次登录。
  8. 请注意,永不过期且无法撤销的刷新令牌会为用户提供无限制访问权限,因此请小心执行。

  9. 在我的回答here中,您可以看到如何使用Identity 2处理刷新令牌。您可以考虑切换到身份2。

  10. 我想我已经提到了一切。如果我错过了什么或者有什么不清楚的地方,请告诉我。