首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场

Microsoft
EN

Stack Overflow用户
提问于 2014-08-02 14:53:45
回答 1查看 5.3K关注 0票数 2

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

代码语言:javascript
运行
复制
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获取令牌的代码如下:

代码语言:javascript
运行
复制
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)的代码:

代码语言:javascript
运行
复制
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;
        }
    }

解码后的令牌(使用google令牌解码器,如下所示)

代码语言:javascript
运行
复制
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 2中解码JWT令牌的正确方法) Owin中是否有任何跟踪设施可以提供身份验证管道中发生的事情?

我正在使用微软自己的3.0-rc1。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-05 02:36:03

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

从ACS接收JWT令牌后,我需要正确设置授权

代码语言:javascript
运行
复制
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如何发送令牌。

代码语言:javascript
运行
复制
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"]
            });
    }
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25096298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档