【问题标题】:Microsoft Owin UseJwtMicrosoft Owin UseJwt
【发布时间】:2014-09-25 14:32:08
【问题描述】:

我在使用 UseJwtBearerAuthentication 方法时遇到了困难,我正在使用 Microsoft Azure ACS 来获取令牌(使用服务标识)。 JWT 令牌可以很好地返回到我的测试程序。在测试程序中,令牌被发送到 MVC WebAPI 2。(当令牌从 Azure Active Directory 获取时,WAAD 身份验证工作正常)

public partial class Startup
{
    private const string Issuer = "https://bluebeam-us-east.accesscontrol.windows.net/";
    public void ConfigureAuth(IAppBuilder app)
    {
        string CertificateThumbprint = "99B25E3E31FCD24F669C260A743FBD508D21FE30";
        var audience = ConfigurationManager.AppSettings["ida:Audience"];
        app.UseErrorPage(new ErrorPageOptions()
                {
                    ShowEnvironment = true,
                    ShowCookies = false, 
         ShowSourceCode = true,
                    });



        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience =  audience ,
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
            });
        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
        {
            AllowedAudiences = new[] { audience },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new X509CertificateSecurityTokenProvider(Issuer, X509CertificateHelper.FindByThumbprint(StoreName.My,StoreLocation.LocalMachine,CertificateThumbprint).First())
            },
        });
    }

从ACS获取Token的代码如下:

private async void GetJwtToken()
{
    try
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(IdP.Authority);
            var content = new FormUrlEncodedContent(new Dictionary<String, String>
            {
                {"grant_type","client_credentials"},
                {"client_id", IdP.UserName},
                {"client_secret", IdP.Password},
                {"scope", IdP.Resource}
            });
            var response = await client.PostAsync("v2/OAuth2-13", content);
            response.EnsureSuccessStatusCode();
            var jwtdata = await response.Content.ReadAsStringAsync();
            var jwt = JsonConvert.DeserializeObject<Token>(jwtdata);
            AccessToken = jwt.access_token;
            TokenType = jwt.token_type;
            long expire;
            if (long.TryParse(jwt.expires_in, out expire))
            {
                ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expire);
            }
            Authorization = AccessToken;
        }
    }
    catch (HttpRequestException re)
    {
        Response = re.Message;
    }
}

请求资源的代码(WebAPI):

private async void WebApiRequestCall()
    {
        try
        {
            ConfigureSsl();
            using (var client = new HttpClient())
            {
                client.BaseAddress = _baseAddress;
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                if (!String.IsNullOrWhiteSpace(Authorization))
                    client.DefaultRequestHeaders.Add("Authorization", Authorization);
                var response = await client.GetAsync(WebApiRequest);
                response.EnsureSuccessStatusCode();
                Response = await response.Content.ReadAsStringAsync();
            }
        }
        catch (HttpRequestException e)
        {
            Response = e.Message;
        }
    }

解码后的Token(使用google token解码器如下)

Header
{
    "x5t": "mbJePjH80k9mnCYKdD-9UI0h_jA", 
    "alg": "RS256", 
    "typ": "JWT"
}
Claims
{
    "identityprovider": "https://bluebeam-us-east.accesscontrol.windows.net/", 
    "iss": "https://bluebeam-us-east.accesscontrol.windows.net/", 
    "http://schemas.microsoft.com/identity/claims/identityprovider": "revu", 
    "exp": 1406957036, 
    "nbf": 1406956676, 
    "aud": "https://bluebeam.com/Bluebeam.Licensing.WebApi/"
}

所以我有以下问题:

1) 使用 JwtBearerToken 是用于解码来自 ACS 的 JWT 令牌的正确方法 2) Owin 中是否有任何跟踪设施可以提供身份验证管道中发生的情况?

我正在使用 Microsoft Own 3.0-rc1。

【问题讨论】:

  • 看起来你已经明白了,但你有没有看过 System.IdentityModel.Tokens 命名空间中的 JSON Web 令牌处理程序?你可以在 NuGet 上找到它,它是一个为创建和验证 JSON Web 令牌 (JWT) 而设计的 SecurityTokenHandler。 msdn.microsoft.com/en-us/library/…
  • 嗨 Mitch,是的,我确实看过课程,我希望 OWIN 文档更清晰。 (在绝望中,我编写了自己的令牌处理程序以确保它不会在发送方出现问题),然后我发现 OWIN 想要在标头中使用“beaer token”

标签: authentication azure asp.net-web-api acs jwt


【解决方案1】:

似乎我的代码中有一个错误,在将客户端请求发送到 WebAPI 时,我没有为 OWIN 设置正确的“承载标头”。

从 ACS 收到 JWT Token 后,我需要正确设置授权

private async void GetJwtToken()
    {
        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(IdP.Authority);
                var content = new FormUrlEncodedContent(new Dictionary<String, String>
                {
                    {"grant_type","client_credentials"},
                    {"client_id", IdP.UserName},
                    {"client_secret", IdP.Password},
                    {"scope", IdP.Resource}
                });
                var response = await client.PostAsync("v2/OAuth2-13", content);
                response.EnsureSuccessStatusCode();
                var jwtdata = await response.Content.ReadAsStringAsync();
                var jwt = JsonConvert.DeserializeObject<Token>(jwtdata);
                IdP.AccessToken = jwt.access_token;
                IdP.TokenType = jwt.token_type;
                long expire;
                if (long.TryParse(jwt.expires_in, out expire))
                {
                    IdP.ExpiresOn = DateTimeOffset.UtcNow.AddSeconds(expire);
                }
                // Ensure that Correct Authorization Header for Owin
                Authorization = String.Format("{0} {1}", "Bearer", IdP.AccessToken);**
            }
        }
        catch (HttpRequestException re)
        {
            Response = re.Message;
        }
    }

我们还需要在 WebAPI 上支持对称密钥,这取决于 ACS 发送令牌的方式

public void ConfigureAuth(IAppBuilder app)
    {
        var thumbPrint = ConfigurationManager.AppSettings["ida:Thumbprint"];
        var audience = ConfigurationManager.AppSettings["ida:Audience"];
        var trustedTokenPolicyKey = ConfigurationManager.AppSettings["ida:SymmetricKey"];

        app.UseErrorPage(new ErrorPageOptions()
                {
                    ShowEnvironment = true,
                    ShowCookies = false,
                    ShowSourceCode = true,
                });

        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions()
        {
            AllowedAudiences = new[] {audience},
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new X509CertificateSecurityTokenProvider(Issuer,
                    X509CertificateHelper.FindByThumbprint(StoreName.My, StoreLocation.LocalMachine, thumbPrint)
                        .First()),
                new SymmetricKeyIssuerSecurityTokenProvider(Issuer, trustedTokenPolicyKey),
            },
        });
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Audience = audience,
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
            });
    }

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 2017-12-21
    • 2021-06-18
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2015-01-08
    • 2015-12-02
    • 2018-01-29
    相关资源
    最近更新 更多