即使使用 Microsoft.Azure.Mobile SDK 正确,JWT 令牌也未得到验证

JWT token isn't validated even if it's correct using Microsoft.Azure.Mobile SDK

我正在使用 Microsoft.Azure.Mobile SDK 来实现服务器代码。

OWIN启动代码如下:

public void ConfigureAuth(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();
    new MobileAppConfiguration().ApplyTo(config);
    app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
    {
        SigningKey = ConfigurationManager.AppSettings["SigningKey"],
        ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
        ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
        TokenHandler = config.GetAppServiceTokenHandler()
    });
    app.UseWebApi(config);
}

令牌生成代码:

Claim[] claims = new Claim[]
{
    new Claim("sub", "SampleSubject"),
    new Claim("Id", Convert.ToString(Users[0].user_id)),
    new Claim("name", Users[0].name),
    new Claim("surname", Users[0].surname),
    new Claim(ClaimTypes.Role, "user")
};
var token = AppServiceLoginHandler.CreateToken(claims, ConfigurationManager.AppSettings["SigningKey"], ConfigurationManager.AppSettings["ValidAudience"], ConfigurationManager.AppSettings["ValidIssuer"], TimeSpan.FromDays(30));
return token.RawData;

示例 JWT 令牌是 eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJHcnViZXJBUEkiLCJJZCI6IjMyODkwIiwibmFtZSI6IkRhdmlkZSIsInN1cm5hbWUiOiJCb25ldHRhIiwicm9sZSI6InVzZXIiLCJ2ZXIiOiIzIiwiaXNzIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6MjM1MzEvIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6MjM1MzIvIiwiZXhwIjoxNTAyNDYyNDQzLCJuYmYiOjE0OTk4NzA0NDN9.b5VhWzvkaEumutPZpLzImcAy4NotXCSgUIqLltVUQWI

根据以下屏幕截图,令牌有效

对于下面的代码,

 [Authorize]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5 
    public string Get(int id)
    {

        try
        {
            ClaimsPrincipal claims;
            AppServiceTokenHandler s = new AppServiceTokenHandler(new HttpConfiguration());
            s.TryValidateLoginToken(Request.Headers.Authorization.Parameter, ConfigurationManager.AppSettings["SigningKey"], new[] { ConfigurationManager.AppSettings["ValidAudience"] }, new[] { ConfigurationManager.AppSettings["ValidIssuer"] }, out claims);

            AppServiceTokenHandler.ValidateToken(Request.Headers.Authorization.Parameter, ConfigurationManager.AppSettings["SigningKey"], ConfigurationManager.AppSettings["ValidAudience"], ConfigurationManager.AppSettings["ValidIssuer"]);
        }
        catch (Exception ex)
        {

            throw;
        }

        return "value";
    }

'/Get' 请求失败,返回 HTTP 401。 但是对于相同的 JWT 令牌 'Get/5' returns HTTP 200(手动验证令牌)。

问题是,当我使用 Authorize 属性时,api returns 401.

根据你的描述,我这边查了这个问题

访问受保护的网站API

综上所述,您可以参考上面的屏幕截图并使用您的 api 端点进行检查。另外,您可以参考AppServiceTokenHandler.cs and HmacSigningCredentials.cs for implementing your custom TokenHandler to troubleshoot this issue. Moreover, you could refer to adrian hall's book about Custom Authentication .