如何在已存在安全REST端点时验证SOAP服务中的标记

时间:2016-08-23 19:00:30

标签: c# jwt identityserver3

我有一点Frankenstien服务,因为它有相同代码库在同一URL上托管的SOAP和REST的端点。我使用客户端凭据授权流来成功保护REST端点,但是希望使用相同的流程来保护SOAP调用。 startup.cs初始化身份服务器承载令牌身份验证,如下所示:

JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = ConfigurationManager.AppSettings["IdentityServerUrl"],
    RequiredScopes = new[] { ConfigurationManager.AppSettings["IdentityServerScopes"] }
});

对于REST端点,我添加了一个

[Authorize]

代码装饰,一切正常。对于SOAP方面,我重新设置了密码字段并通过它发送了令牌,并且可以像这样解码它:

string sPassword = request.Authentication.Password;
if (sPassword.Contains("."))
{
    "\nAccess Token (decoded):".ConsoleGreen();

    var parts = sPassword.Split('.');
    var header = parts[0];
    var claims = parts[1];

    Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(header))));
    Console.WriteLine(JObject.Parse(Encoding.UTF8.GetString(Base64Url.Decode(claims))));
}

我可以看到声明,但这并不能验证令牌。从这里开始,我将一个ValidateToken方法拼凑在一起,该方法抛出了有关签名验证失败的异常。无法解析SecurityKeyIdentifier。我确信所有内容都已通过IdentityServer3证书签名,但我仍然试图创建证书。我的KeyStore中没有任何证书,并且想要一个并不要求我在KeyStore中插入证书的解决方案。这是尝试:

public static bool VerifyToken(string token)
{
    const string thumbPrint = "6bf8e136eb36d4a56ea05c7ae4b9a45b63bf975d"; // correct thumbprint of certificate
    var cert = X509CertificateHelper.FindByThumbprint(StoreName.My, StoreLocation.LocalMachine, thumbPrint).First();

    var validationParameters = new TokenValidationParameters()
    {
        //IssuerSigningToken = new BinarySecretSecurityToken(_key),
        IssuerSigningToken = new X509SecurityToken(cert),
        ValidAudience = "https://securityeli.twcable.com/core/resources",
        ValidIssuer = "https://securityeli.twcable.com/core",
        ValidateLifetime = true,
        ValidateAudience = true,
        ValidateIssuer = true
        //ValidateIssuerSigningKey = true
    };

    var tokenHandler = new JwtSecurityTokenHandler();
    SecurityToken validatedToken = null;
    try
    {
        tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
    //... manual validations return false if anything untoward is discovered
    return validatedToken != null;
}

public class X509CertificateHelper
{
    public static IEnumerable<X509Certificate2> FindByThumbprint(StoreName storeName, StoreLocation storeLocation, string thumbprint)
    {
        var store = new X509Store(storeName, storeLocation);
        store.Open(OpenFlags.ReadOnly);
        var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);

        foreach (var certificate in certificates)
        {
            yield return certificate;
        }

        store.Close();
    }
}

当前进程无法正常工作,因为我的密钥库中没有密钥。 BinarySecretSecurityToken失败了,因为我不知道密钥长度?

我还要回到房子的REST端,它使用Authorize标签验证持票人令牌,所以我应该可以访问证书,但不知道如何将其从应用。我可以在Startup中看到它通过了我无法访问的IAPPBuilder应用程序。

两个问题是如何创建一个证书来验证在C#中在IdentityServer3中创建的令牌?我可以以某种方式检索该证书吗?

1 个答案:

答案 0 :(得分:0)

在尝试了多条路径之后,我终于找到了可行的方法,我会尝试捕获相关部分,以防其他人试图做同样的事情。

首先,我将传入的令牌分成了它的部分:

    var parts = sPassword.Split('.');
    var header = parts[0];
    var claims = parts[1];

    var token = new JwtSecurityToken(sPassword);

然后我设置了一些变量并调用了自定义VerifyToken方法:

    CustomResponse customResponse = null;
    SecurityToken validatedToken = null;
    ClaimsPrincipal claimsPrincipal = null;

    if (VerifyToken(sPassword, ref customResponse, ref validatedToken, ref claimsPrincipal))
    {
        // Process SOAP request after authentication
    }
    else
        return customResponse; // token wasn't authenticated, and not authorized message was set in the VerifyToken method

VerifyToken方法如下所示:

    public static bool VerifyToken(string token, ref CustomResponse customResponse, ref SecurityToken validatedToken, ref ClaimsPrincipal claimsPrincipal)
    {
            // This was the biggest challenge in finding the cert that is used to validate the token
        var certString = "Found in the CallbackController.cs in the IdentityServer3.Samples repository"
        var cert = new X509Certificate2(Convert.FromBase64String(certString));

            // Setting what you'd like the authorization to validate.
        var validationParameters = new TokenValidationParameters()
        {
            IssuerSigningToken = new X509SecurityToken(cert),
            ValidAudience = ConfigurationManager.AppSettings["IdentityServerUrl"] + "/resources",
            ValidIssuer = ConfigurationManager.AppSettings["IdentityServerUrl"],
            ValidateLifetime = true,
            ValidateAudience = true,
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        try
        {
            claimsPrincipal = tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
        }
        catch (SecurityTokenValidationException e)
        {
            //HttpContext.Current.Response.StatusCode = 401;
            //statusCode = HttpStatusCode.Unauthorized;
            customResponse = new CustomResponse();

            customResponse.ServiceReturnStatus = new ServiceReturnStatus();
            customResponse.ServiceReturnStatus.ReturnCode = -401;
            customResponse.ServiceReturnStatus.ReturnMessage = "Unauthorized";
        }
        catch (Exception e)
        {
            //HttpContext.Current.Response.StatusCode = 403;
            //statusCode = HttpStatusCode.InternalServerError;
            customResponse = new CustomResponse();

            customResponse.ServiceReturnStatus = new ServiceReturnStatus();
            customResponse.ServiceReturnStatus.ReturnCode = -403;
            customResponse.ServiceReturnStatus.ReturnMessage = "Internal Server Error";
        }
        //... manual validations return false if anything untoward is discovered
        return validatedToken != null;
    }

    private string GetClaimFromPrincipal(ClaimsPrincipal principal, string claimType)
    {
        var uidClaim = principal != null && principal.Claims != null ? principal.Claims.FirstOrDefault(s => s.Type == claimType) : null;
        return uidClaim != null ? uidClaim.Value : null;
    }

我还添加了一个GetClaimFromPrincipal,可用于从委托人那里获得索赔。

那就是它,它看起来并不复杂,但它确实花了我很多试验和错误才能让它发挥作用。我仍然喜欢使用Owin Startup信息验证/授权令牌的选项,因为我所做的一切基本上都是加载我在Startup.cs中加载的所有信息,如下所示:

    app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = ConfigurationManager.AppSettings["IdentityServerUrl"],
        RequiredScopes = new[] { ConfigurationManager.AppSettings["IdentityServerScopes"] }
    });