簡體   English   中英

Webapi 2.0如何在訪問令牌過期時實現刷新JWT令牌

[英]Webapi 2.0 how to implement refresh JWT token when access token expired

我在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資源,他必須再次登錄並更新令牌! 這是我所不希望的,因為應用程序會話超時時間尚未過去,所以用戶不應提示再次登錄。

我如何刷新令牌而不強制用戶再次登錄。

如果我在下面給出的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
        {

        }

    }

}

上面是一個示例代碼來說明該問題,它可能有一些錯字。

這可以通過單獨的持久性刷新令牌來完成。 網址http://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web-token/的不錯的教程

我有一些評論:

  1. 訪問令牌應由客戶端保存,而不是在服務器上的會話中保存。 刷新令牌的計數相同。 這樣做的原因是通常沒有會話。 智能客戶端無需會話即可處理令牌,MVC網站可以使用Cookie,而API不知道會話。 這不是禁止的,但是再次,您將需要擔心會話到期,並且在重新啟動服務器時所有用戶都必須再次登錄。

  2. 如果要實現OAuth,請閱讀規范 在這里,您將找到實現刷新令牌所需的一切。

  3. 在TokenController中,您處理登錄。 在那里,您還應該檢查其他條件

    • grant_type =密碼
    • 內容類型必須為“ application / x-www-form-urlencoded”
    • 僅當通過安全線路(https)發送時,才應處理該請求。
  4. 當獲得了access_token時,並且僅當請求了refresh_token時,您才應在access_token中包括refresh_token

  5. 客戶端應用程序 (grant_type = client_credentials)不需要刷新令牌,因為那些使用clientid / secret獲得訪問令牌的應用程序。 擴展TokenController以允許client_credentials流。 請注意:刷新令牌僅供用戶使用,只有在可以將其保密的情況下才應使用。 刷新令牌非常強大,因此請謹慎處理。

  6. 為了刷新訪問令牌,您需要將刷新令牌發送到端點。 在您的情況下,您可以擴展TokenController以允許refresh_token請求。 您需要檢查:

    • grant_type =刷新令牌
    • 內容類型必須為“ application / x-www-form-urlencoded”
  7. 刷新令牌有幾種方案,您也可以將它們組合在一起:

    • 將刷新令牌保存在數據庫中。 每次使用刷新令牌時,都可以將其從數據庫中刪除,然后保存新的刷新令牌,該刷新令牌也將在新的access_token中返回。
    • 將刷新令牌設置為更長的生命周期,並且在刷新訪問令牌時不要刷新它。 在這種情況下,返回的access_token不包含新的刷新令牌。 這樣,您將需要在refresh_token到期后再次登錄。
  8. 請注意,永不過期且無法撤消的刷新令牌為用戶提供了無限的訪問權限,因此請謹慎實施。

  9. 在我的回答中您可以看到如何使用身份2處理刷新令牌。您可以考慮切換到身份2。

我想我已經提到了一切。 如果我錯過了某些內容或不清楚的內容,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM