使用IdentityServer3调用Web API时出现401未经授权

2024-04-23

我正在尝试使用 IdentityServer3 和客户端凭据流程来设置一个简单的示例。该示例包含一个控制台客户端,使用从 IdentityServer 接收的令牌调用 Web API 资源。 Web API 和 IdentityServer 托管在 IIS 中。

我设法使用以下方法从 IdentityServer 获取令牌:

  var client = new TokenClient(
            "https://machine+domain/WebHostedId3/connect/token",
            "client",
            "secret");

但是当我尝试使用以下方式调用 Web API 时:

 var client = new HttpClient();

 client.SetBearerToken(token);

 var response = client.GetStringAsync("http://localhost/WebHostedApi/api/products").Result;

我收到 401(响应状态代码并不表示成功:401(未经授权)。

IdentityServer的设置如下:

public class Clients
{
    public static List<Client> Get()
    {
        return new List<Client>
        {
            new Client
            {
                ClientName = "Client Credentials Flow Client",
                Enabled = true,
                ClientId = "client",
                AccessTokenType = AccessTokenType.Reference,
                ClientSecrets = new List<Secret>
                {
                    new Secret("secret".Sha256())
                },

                Flow = Flows.ClientCredentials,

                AllowedScopes = new List<string>
                {
                    "api"
                }
            }
        };
    }
}

public class Scopes
{
    public static IEnumerable<Scope> Get()
    {
        return new[]
            {
                new Scope
                {
                    Name = "api",
                    DisplayName = "API Scope",
                    Type = ScopeType.Resource,
                    Emphasize = false
                }
            };
    }
}

 public class Startup
 {
    public void Configuration(IAppBuilder appBuilder)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
            .CreateLogger();

        var factory = new IdentityServerServiceFactory()
            .UseInMemoryUsers(new System.Collections.Generic.List<InMemoryUser>())
                    .UseInMemoryClients(Clients.Get())
                    .UseInMemoryScopes(Scopes.Get());

        var options = new IdentityServerOptions
        {
            Factory = factory,
        };

        appBuilder.UseIdentityServer(options);
    }
}

网络 API:

public static class WebApiConfig
{
    public static HttpConfiguration Register()
    {
        var config = new HttpConfiguration();

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
           name: "DefaultRouting",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
           );

        // require authentication for all controllers
        config.Filters.Add(new AuthorizeAttribute());

        return config;
    }
}

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        Log.Logger = new LoggerConfiguration()
            .WriteTo.Trace(outputTemplate: "{Timestamp} [{Level}] ({Name}){NewLine} {Message}{NewLine}{Exception}")
            .CreateLogger();

        app.UseIdentityServerBearerTokenAuthentication(
            new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "machine+domain:443",
                ValidationMode = ValidationMode.ValidationEndpoint,
                RequiredScopes = new[] { "api" }
            });

        app.UseWebApi(WebApiConfig.Register());
    }
}

用于 SSL 的证书是使用 IIS 创建自签名证书功能创建的,并连接到 IdentityServer 的 https 绑定。除了“响应状态代码不表示成功:401(未经授权)”异常之外,我找不到更多详细信息。来自 IdentityServer 的日志看起来不错。帮助将不胜感激。


我知道回复已经很晚了。尝试将所有 nuget,尤其是 Newtonsoft.Json 更新到 8.0.3

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用IdentityServer3调用Web API时出现401未经授权 的相关文章

随机推荐