IdentityServer4 IdentityServer3.AccessTokenValidation [英] IdentityServer4 IdentityServer3.AccessTokenValidation

查看:217
本文介绍了IdentityServer4 IdentityServer3.AccessTokenValidation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家新年快乐...

我配置了IdentityServer4,并且可以成功进行ASP.net Core Web api调用. 但是对于asp.net Framework 4.5.2 Web API, 我从{.NET Framework Web api中收到{响应状态代码不表示成功:401(未授权).")错误.我想问一下您的帮助和意见.

I configured an IdentityServer4, and I can make successful ASP.net Core web api calls. But for asp.net framework 4.5.2 web apis, I got {"Response status code does not indicate success: 401 (Unauthorized)."} error from a .NET framework web api. I want to ask your help and opinion.

我用IS4搜索了该主题,并找到了一些有关IdentityServer3.AccessTokenValidation兼容性的条目.根据答复,我加载了一个签名证书,并命名为AddSigningCredential而不是AddTemporarySigninCredential. x509certificate是本地创建的证书.我将IdentityServer3.AccessTokenValidation版本更新为v2.13.0.

I seached the topic with IS4, and found some entries about IdentityServer3.AccessTokenValidation compatibility. And according to the replies, I loaded a signing cert and called AddSigningCredential instead of AddTemporarySigninCredential. x509certificate is a local created cert. and I updated IdentityServer3.AccessTokenValidation version to v2.13.0.

还是我得到了错误. 感谢您的帮助.

Still I got the error. Any help is appreciated.

致谢,并感谢您的辛勤努力.

Regards and thanks for your great effort.

IdentityServer 4端: Startup.cs

IdentityServer 4 side: Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
                services
                .AddIdentityServer()                
                //.AddTemporarySigningCredential()
                .AddSigningCredential(x509Certificate)
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources())
                .AddInMemoryClients(Config.GetClients())
                .AddAspNetIdentity<ApplicationUser>();
}

Config.cs

Config.cs

    public static IEnumerable<ApiResource> GetApiResources()
            {
                return new List<ApiResource>
                {
                    new ApiResource("AuthorizationWebApi","Authorization Web API .NET Core"),
                    new ApiResource("AuthorizationWebApiNetFramework","Authorization Web API NET Framework"),
                new ApiResource("api1", "Empty Test Api")
                };

            }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client> {
new Client {
                    ClientId = "silicon",
                    ClientName = "console app",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets = { new Secret("abcdef".Sha256())},
                    AllowedScopes = new List<string>{
                    "AuthorizationWebApiNetFramework"
                    }

                },
                new Client
                {
                    ClientId = "MYUX",
                    ClientName = "MYUX MVC Client",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    RequireConsent = false,
                    ClientSecrets= {new Secret("abcdef".Sha256()) },
                    RedirectUris = { "http://localhost:5002/signin-oidc" },
                    PostLogoutRedirectUris = {"http://localhost:5002"},

                    AllowedScopes = {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,                        
                        "custom.profile",
                        "AuthorizationWebApi",
                        "AuthorizationWebApiNetFramework"
                    },
                    AllowOfflineAccess = true
                }
            };
        }

.NET FrameworkAPİSide

.NET Framework APİ Side

public void Configuration(IAppBuilder app)
        {
            //ConfigureAuth(app);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "http://www.abcdefgh.com:5000",
                ValidationMode = ValidationMode.ValidationEndpoint,
                RequiredScopes = new[] { "AuthorizationWebApiNETFramework" }

            });
            //configure web api
            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();

            //require authentication for all controllers

            config.Filters.Add(new AuthorizeAttribute());

            app.UseWebApi(config);
        }

呼叫方:

try
            {
                ViewData["Message"] = "Authorization Test.";
                var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
                var authorizationApiClient = new HttpClient();
                authorizationApiClient.SetBearerToken(accessToken);
                var content = await authorizationApiClient.GetStringAsync("http://localhost:13243/values");
                return View();
            }
            catch (Exception ex)
            {
                throw;
            }

或通过控制台应用程序...

or by a console app...

try
{
    // discover endpoints from metadata
    var disco = await DiscoveryClient.GetAsync("http://www.abcdefgh.com:5000");

    var tokenClient = new TokenClient(disco.TokenEndpoint, "silicon", "abcdef");
    var tokenResponse = await tokenClient.RequestClientCredentialsAsync("AuthorizationWebApiNetFramework");

    if (tokenResponse.IsError)
    {
        Console.WriteLine(tokenResponse.Error);
        return;
    }

    Console.WriteLine(tokenResponse.Json);

    var client = new HttpClient();
    client.SetBearerToken(tokenResponse.AccessToken);

    var response = await client.GetAsync("http://localhost:13243/values");
    if (!response.IsSuccessStatusCode)
    {
        Console.WriteLine(response.StatusCode);
    }
    else
    {
        var content = await response.Content.ReadAsStringAsync();
        Console.WriteLine(JArray.Parse(content));
    }
}
catch (Exception)
{
   throw;
}     

:在Api方面4.5.2:我注释了该行 ValidationMode = ValidationMode.ValidationEndpoint.我通过遵循IS3文档添加了这一行.谢谢大家.

On 4.5.2 Api side: I commented out the line ValidationMode = ValidationMode.ValidationEndpoint. I added this line by following IS3 documentation. Thanks everyone.

推荐答案

删除WebAPI访问令牌验证中间件中的以下行.

Remove the following line in the WebAPI accesstoken validation middleware.

ValidationMode = ValidationMode.ValidationEndpoint

结果应如下所示:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions 
{
     Authority = "http://www.abcdefgh.com:5000",
     RequiredScopes = new[] { "AuthorizationWebApiNETFramework" }
});

这篇关于IdentityServer4 IdentityServer3.AccessTokenValidation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆