Protecting webapi with IdentityServer and Autofac - can't get claims

蹲街弑〆低调 提交于 2020-01-25 16:34:22

问题


I'm trying to protect my webapi with IdentityServer and OpenID Connect using Autofac. I'm using OWIN. But for some reason I can't get claims of the user. It seems that AccessTokenValidation is not triggered at all. That makes me think there is something wrong in the order of my declarations at my startup. Here is my startup.

public class Startup {

    public void Configuration(IAppBuilder appBuilder) {

        // Add authentication
        this.AddAuthentication(appBuilder);

        HttpConfiguration config = new HttpConfiguration();
        var container = CreateAutofacContainer();

        var resolver = new AutofacWebApiDependencyResolver(container);
        config.DependencyResolver = resolver;  
        WebApiConfig.Register(config);
        config.EnsureInitialized();

        // Register config - you can't add anything to pipeline after this
        appBuilder.UseAutofacMiddleware(container);
        appBuilder.UseAutofacWebApi(config);
        appBuilder.UseWebApi(config);       
    }

    private static IContainer CreateAutofacContainer() {

        var autofacBuilder = new ContainerBuilder();

        var assembly = Assembly.GetExecutingAssembly();

        // Register your Web API controllers.
        autofacBuilder.RegisterApiControllers(assembly);

        // For general logging implementation
        autofacBuilder.RegisterType<ConsoleLogger>().As<ILogger>();

        // Create empty usage context to be filled in OWIN pipeline
        IUsageContext usageContext = new RuntimeUsageContext();
        autofacBuilder.RegisterInstance(usageContext).As<IUsageContext>().SingleInstance();

        // We need to get usage context builded
        autofacBuilder.RegisterType<OIDCUsageContextProvider>().InstancePerRequest();

        var container = autofacBuilder.Build();
        return container;
    }

    private void AddAuthentication(IAppBuilder app) {

        var options = new IdentityServerBearerTokenAuthenticationOptions();

        options.Authority = "MYAUTHORITY";
        options.RequiredScopes = new[] { "openid", "profile", "email", "api" };
        options.ValidationMode = ValidationMode.ValidationEndpoint;
        app.UseIdentityServerBearerTokenAuthentication(options);

        // Add local claims if needed
        app.UseClaimsTransformation(incoming => {

            // either add claims to incoming, or create new principal
            var appPrincipal = new ClaimsPrincipal(incoming);
            // incoming.Identities.First().AddClaim(new Claim("appSpecific", "some_value"));

            return Task.FromResult(appPrincipal);
        });
    }

I'm using hybrid flow and api is called from SPA-application. I've verified (by calling my identity server's endpoint directly) that access token is valid and there are claims available. I also downloaded IdentityServer.AccessTokenValidation project and attached it as a reference. When I set some breakpoints to methods in that project, they never get called. That is why I think there is something wrong with my startup and OWIN pipeline.

I've declared UsageContext in my startup. It is a class I'm using to collect claims and some configuration settings - to be injected to actual controllers. I think it would be nice way to handle this, so in controllers there is always valid UsageContext available.

I've read a lot of samples and examples but still haven't found exactly same situation. I'll appreciate any attempts to point me into right direction.

Regards, Borre


回答1:


Could it be your registration of UsageContext as a Singleton? You mention this class contains claims, so this object should be resolved once pr http request - shouldn't it?




回答2:


It turned out that there was some mysterious line in AccessTokenValidation - library that didn't work. I use that library to get claims. After changing the line everything seemed to work.

So basically my question is closed now and stuff works. But I'm still not totally convinced this is the right way to do this.

Thanks John for your comments!



来源:https://stackoverflow.com/questions/38712088/protecting-webapi-with-identityserver-and-autofac-cant-get-claims

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!