IdentityServer4 IdentityServer3.AccessTokenValidation

时间:2017-01-02 10:37:00

标签: identityserver3 identityserver4

祝大家新年快乐......

我配置了一个IdentityServer4,我可以成功完成ASP.net Core web api调用。 但对于asp.net framework 4.5.2 web apis, 我得到{“响应状态代码不表示成功:401(未授权)。”}来自.NET框架web api的错误。我想问你的帮助和意见。

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

我还是得到了错误。 任何帮助表示赞赏。

感谢您的努力。

IdentityServer 4端: 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

    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 Framework AP侧面

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;
            }

或通过控制台应用...

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;
}     

编辑:在4.5.2 Api方面:我注释掉了这条线 ValidationMode = ValidationMode.ValidationEndpoint。我按照IS3文档添加了这一行。谢谢大家。

2 个答案:

答案 0 :(得分:5)

删除WebAPI accessstoken验证中间件中的以下行。

ValidationMode = ValidationMode.ValidationEndpoint

结果应如下所示:

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

答案 1 :(得分:0)

就我而言,我启用了以下日志:https://identityserver.github.io/Documentation/docsv2/consuming/diagnostics.html

  

默认情况下,Katana使用.NET中的TraceSource机制进行日志记录。将以下代码段添加到您的配置文件中,以启用对文件的日志记录:

<system.diagnostics>
  <trace autoflush="true" />

  <sources>
    <source name="Microsoft.Owin">
      <listeners>
        <add name="KatanaListener" />
      </listeners>
    </source>
  </sources>

  <sharedListeners>
    <add name="KatanaListener"
          type="System.Diagnostics.TextWriterTraceListener"
          initializeData="katana.trace.log"
          traceOutputOptions="ProcessId, DateTime" />
  </sharedListeners>

  <switches>
    <add name="Microsoft.Owin"
          value="Verbose" />
  </switches>
</system.diagnostics>

然后我在WebAPI文件夹日志文件“ katana.trace.log”中看到了根本原因:

    Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware Error: 0 : Authentication failed
System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
   at IdentityServer3.AccessTokenValidation.ValidationEndpointTokenProvider.<ReceiveAsync>d__1.MoveNext()
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine)
   at IdentityServer3.AccessTokenValidation.ValidationEndpointTokenProvider.ReceiveAsync(AuthenticationTokenReceiveContext context)
   at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationHandler.<AuthenticateCoreAsync>d__0.MoveNext()

将Newtonsoft.Json从6.0升级到9.01后,它开始工作。