。net 4.6 web api2 401未经身份服务器4授权

问题描述 投票:0回答:2

我已经在.net核心应用程序中拥有工作的身份服务器4。

namespace IdentityServer
{
    public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>
            {
                new ApiResource("myresourceapi", "My Resource API")
                {
                    Scopes = {new Scope("apiscope")}
                }
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new[]
            {
                // for public api
                new Client
                {
                    ClientId = "secret_client_id",
                    AllowedGrantTypes = GrantTypes.ClientCredentials,
                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "apiscope" }
                }
            };
        }
    }
}

namespace IdentityServer
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddOperationalStore(options =>
            {
                options.EnableTokenCleanup = true;
                options.TokenCleanupInterval = 30; // interval in seconds
             })
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseIdentityServer();
            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
        }
    }
}

问题是,现在我需要向.net 4.6 Web api2(非核心)发出经过身份验证的请求。而且IdentityServer4.AccessTokenValidation包对此不起作用。根据此问题(https://stackoverflow.com/questions/41992272/is-it-possible-to-use-identity-server-4-running-on-net-core-with-a-webapi-app-r),我所要做的就是使用与身份服务器3相同的包(IdentityServer3.AccessTokenValidation)。这是我在webapi中实现的代码2

using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Host.SystemWeb;
using IdentityModel.Extensions;
using System.Web.Http;

[assembly: OwinStartup(typeof(WebApplication10.Startup))]

namespace WebApplication10
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44357",

                // For access to the introspection endpoint
                ClientId = "secret_client_id",
                ClientSecret = "secret".ToSha256(),
                RequiredScopes = new[] { "apiscope" }
            });

        }
    }
}

namespace WebApplication10.Controllers
{
    public class ValuesController : ApiController
    {
        [Authorize]
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

我一直得到的状态是401未经授权。难道我做错了什么?有什么帮助吗?谢谢。

asp.net-core asp.net-web-api2 identityserver4 identityserver3
2个回答
0
投票

没有日志无法确定您所遇到的问题,但这是我为使其正常工作而做出的一些修复:

  1. 在IdentityServer项目的Statup.cs类上
    • AccessTokenJwtType更改为JWT,IdentityServer4的默认值为at+jwt,但是.Net Framework Api(OWIN / Katana)需要JWT
    • 通过将/resources设置为true,添加EmitLegacyResourceAudienceClaim音频,在IdentityServer4上将其删除。

您可以通过检查https://jwt.ms/"typ"来验证"aud"上的access_token。

var builder = services.AddIdentityServer(                
                options =>
                {
                    options.AccessTokenJwtType = "JWT"; 
                    options.EmitLegacyResourceAudienceClaim = true;
                });
  1. 在.Net Framework Api项目的Statup.cs类上,将ValidationMode设置为ValidationMode.Local,此方法使用的自定义访问令牌验证终结点已在IdentityServer4上删除。
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44357",

                // For access to the introspection endpoint
                ClientId = "secret_client_id",
                ClientSecret = "secret".ToSha256(),
                RequiredScopes = new[] { "apiscope" },
                ValidationMode = ValidationMode.Local,
            });

我有示例工作实现here

我强烈建议您收集API上的日志,这有助于查找您所遇到的实际问题并找到解决方法。 here是在Api上打开OWIN日志的示例。


0
投票

您可以关注CrossVersionIntegrationTests中的示例。

在Identity server4应用中,您可以修改ApiResource以包括ApiSecrets

new ApiResource("api1", "My API"){  ApiSecrets = new List<Secret> {new Secret("scopeSecret".Sha256())}}

并且在您的Web api中,将IdentityServerBearerTokenAuthenticationOptions配置为:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = "http://localhost:5000",
    ValidationMode = ValidationMode.ValidationEndpoint,
    ClientId = "api1",
    ClientSecret = "scopeSecret",
    RequiredScopes = new[] { "api1" }
});
© www.soinside.com 2019 - 2024. All rights reserved.