C# 有没有办法检查oauth令牌是否过期?

C# 有没有办法检查oauth令牌是否过期?,c#,asp.net-web-api,oauth,C#,Asp.net Web Api,Oauth,我正在使用oauth令牌访问web api 令牌在1小时后过期。但我想添加功能,以便在到期时生成新的令牌 我发现,在令牌过期的情况下,它会以未经授权的方式发送StatusCode 请让我知道这是否是唯一一个告知令牌过期的状态码。最简单的方法就是尝试用它调用服务。它将拒绝它,如果它是过期的,然后你可以要求一个新的 您还可以保留收到令牌的时间,并使用中的expires\u计算令牌大约何时到期。然后,在到期日后发出新请求之前,您需要请求一个新令牌。我知道这是一篇旧文章,但有一种更直接的方法。如果您从B

我正在使用oauth令牌访问web api

令牌在
1小时后过期
。但我想添加功能,以便在到期时生成新的令牌

我发现,在令牌过期的情况下,它会以
未经授权的方式发送StatusCode


请让我知道这是否是唯一一个告知令牌过期的状态码。

最简单的方法就是尝试用它调用服务。它将拒绝它,如果它是过期的,然后你可以要求一个新的


您还可以保留收到令牌的时间,并使用中的
expires\u计算令牌大约何时到期。然后,在到期日后发出新请求之前,您需要请求一个新令牌。

我知道这是一篇旧文章,但有一种更直接的方法。如果您从Base64格式解码令牌,您可以看到过期日期,然后可以将其与当前日期进行比较

如果要检查此方法是否有效,可以使用它来解码令牌

现在,在C#中,您遇到了一些困难,因为标记包含“.”,无法解码,如果只取出两点之间的中间部分,长度将无效(它应该始终是4的倍数)。为了使中间部分具有正确的长度,您可以添加“=”符号,直到它是多个4

最后,我将日期与当前dat加上一分钟进行比较。因为我不希望一个将在一秒钟内过期的令牌被认为是有效的。您可能希望调整该时间以适应您的目的

这是我的代码:

    /***
     * Check if the string token is expired by decoding it from the Base64 string
     * Some adjustements to the string are necessairy since C# can only decode certain strings.
     * It cannot handle '.' and requires a string has a length that is a multitude of 4.
     * The information we are interrested in is found between the dots.
     * 
     * The token that is given as a parameter should have approximately the following structure:
     * ddddddddddddddddddddd.ddddddddddddddddddddddddddddddddddddd.dddddddddddddddddddddddddddd
     * And should be a valid Oauth token that may or may not be expired
     */
    public static bool isExpired(String token)
    {
        if (token == null || ("").Equals(token))
        {
            return true;
        }

        /***
         * Make string valid for FromBase64String
         * FromBase64String cannot accept '.' characters and only accepts stringth whose length is a multitude of 4
         * If the string doesn't have the correct length trailing padding '=' characters should be added.
         */
        int indexOfFirstPoint = token.IndexOf('.') + 1;
        String toDecode = token.Substring(indexOfFirstPoint, token.LastIndexOf('.') - indexOfFirstPoint);
        while (toDecode.Length % 4 != 0)
        {
            toDecode += '=';
        }

        //Decode the string
        string decodedString = Encoding.ASCII.GetString(Convert.FromBase64String(toDecode));

        //Get the "exp" part of the string
        String beginning = "\"exp\":\"";
        int startPosition = decodedString.LastIndexOf(beginning) + beginning.Length;
        decodedString = decodedString.Substring(startPosition);
        int endPosition = decodedString.IndexOf("\"");
        decodedString = decodedString.Substring(0, endPosition);
        long timestamp = Convert.ToInt64(decodedString);

        DateTime date = new DateTime(1970, 1, 1).AddMilliseconds(timestamp);
        DateTime compareTo = DateTime.Now.AddMinutes(1);

        int result = DateTime.Compare(date, compareTo);

        return result < 0;
    }
/***
*通过从Base64字符串解码字符串令牌,检查其是否过期
*由于C#只能解码某些字符串,因此有必要对字符串进行一些调整。
*它无法处理“.”,并且需要长度为4的字符串。
*我们所关心的信息是在点之间找到的。
* 
*作为参数提供的令牌应具有大致如下结构:
*dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
*并且应该是有效的Oauth令牌,该令牌可能会过期,也可能不会过期
*/
公共静态bool isExpired(字符串标记)
{
if(token==null | |(“”)。等于(token))
{
返回true;
}
/***
*使字符串对FromBase64String有效
*FromBase64String不能接受“.”字符,只接受长度为4的字符串
*如果字符串的长度不正确,则应添加尾随填充“=”字符。
*/
int indexOfFirstPoint=token.IndexOf('.')+1;
字符串toDecode=token.Substring(indexOfFirstPoint,token.LastIndexOf('.')-indexOfFirstPoint);
while(toDecode.Length%4!=0)
{
toDecode+='=';
}
//解码字符串
string decodedString=Encoding.ASCII.GetString(Convert.FromBase64String(toDecode));
//获取字符串的“exp”部分
字符串开头=“\”exp\“:\”;
int startPosition=decodedString.LastIndexOf(开始)+开始.Length;
decodedString=decodedString.Substring(起始位置);
int-endPosition=decodedString.IndexOf(“\”);
decodedString=decodedString.子字符串(0,结束位置);
长时间戳=Convert.ToInt64(解码字符串);
DateTime日期=新的日期时间(1970,1,1).add毫秒(时间戳);
DateTime compareTo=DateTime.Now.AddMinutes(1);
int result=DateTime.Compare(日期,compareTo);
返回结果<0;
}

再次恢复这篇文章,采用@Lavandysh的解决方案,加入
System.IdentityModel.Tokens.Jwt
类;调用此方法以了解令牌在请求之前是否仍然有效:

public bool\u无效(字符串标记)
{
if(string.IsNullOrEmpty(令牌))
{
返回true;
}
var jwtToken=新的JwtSecurityToken(令牌);
返回(jwtToken==null)| |(jwtToken.ValidFrom>DateTime.UtcNow)| |(jwtToken.ValidTo
我在开发Xamarin表单应用程序时遇到了这个问题。这里的主要问题是我无法在项目中安装任何Nuget。所以我决定改进@Lavandysg answer,因为它没有正确提取过期时间戳,也没有正确计算过期时间。下面是我使用正则表达式从令牌中提取过期时间的最后一段代码:

public bool已过期(字符串标记)
{
if(token==null | |(“”)。等于(token))
{
返回true;
}
/***
*使字符串对FromBase64String有效
*FromBase64String不能接受“.”字符,只接受长度为4的字符串
*如果字符串的长度不正确,则应添加尾随填充“=”字符。
*/
int indexOfFirstPoint=token.IndexOf('.')+1;
字符串toDecode=token.Substring(indexOfFirstPoint,token.LastIndexOf('.')-indexOfFirstPoint);
while(toDecode.Length%4!=0)
{
toDecode+='=';
}
//解码字符串
string decodedString=Encoding.ASCII.GetString(Convert.FromBase64String(toDecode));
//获取字符串的“exp”部分
Regex Regex=newregex(“(\“exp\”:)([0-9]{1,})”;
匹配=正则表达式匹配(decodedString);
长时间戳=Convert.ToInt64(match.Groups[2].Value);
DateTime日期=新的日期时间(1970,1,1).AddSeconds(时间戳);
DateTime compareTo=DateTime.UtcNow;
int result=DateTime.Compare(日期,compareTo);
返回结果