Identity Server and web api for user management
Asked Answered
E

1

7

I'm using Identity Server3 for my project, I currently have a website and api being protected by the Id server, this is working fine however because I'm storing the users in the Id Server database I can't really change any user's data from the website like changing the profile picture or any claim value.

In order to solve this I'm thinking in creating an API on top of IdServer, this API will manage the users, changing a password, retrieving users or changing anything related to a user basically, I want to create this API on the sample project where I have my IdServer using Owin mapping.

Right now I have my idServer in the /identity route like this

public class Startup
{
    public void Configuration(IAppBuilder app)
    {

        Log.Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.Trace().CreateLogger();            

        app.Map("/identity", idserverApp =>
         {
             var efConfig = new EntityFrameworkServiceOptions
             {
                 ConnectionString = "IdSvr3Config"
             };

             var options = new IdentityServerOptions
             {
                 SiteName = "Identity server",
                 IssuerUri = ConfigurationManager.AppSettings["idserver:stsIssuerUri"],
                 PublicOrigin = ConfigurationManager.AppSettings["idserver:stsOrigen"],
                 SigningCertificate = Certificate.Get(),
                 Factory = Factory.Configure(efConfig),
                 AuthenticationOptions = AuthOptions.Configure(app),
                 CspOptions = new CspOptions { Enabled = false },
                 EnableWelcomePage=false
             };


             new TokenCleanup(efConfig, 3600 * 6).Start();
             idserverApp.UseIdentityServer(options);
         });

        app.UseIdServerApi();

    }        
}

My api "middleware" is as this

**public static class IdServerApiExtensions
    {
        public static void UseIdServerApi(this IAppBuilder app, IdServerApiOptions options = null)
        {
            if (options == null)
                options = new IdServerApiOptions();            

            if (options.RequireAuthentication)
            {
                var dic = app.Properties;
                JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
                app.UseIdentityServerBearerTokenAuthentication(
                    new IdentityServerBearerTokenAuthenticationOptions
                    {
                        Authority = "https://localhost:44302/identity", //here is the problem, it says not found even though I already mapped idServer to /identity
                        RequiredScopes = new[]
                        {
                        "idserver-api"
                        },
                        ValidationMode=ValidationMode.ValidationEndpoint
                    });
            }
            var config = new HttpConfiguration();
            WebApiConfig.Register(config,options.RequireAuthentication);
            app.UseNinjectMiddleware(() => NinjectConfig.CreateKernel.Value);
            app.UseNinjectWebApi(config);
            app.Use<IdServerApiMiddleware>(options);
        }
    }**

I know is possible I just don't know if it is a good idea to have the api on the same project or not and also I don't know how to do it.

  • Is it a good idea to create this API to manage the users? If not what could I use?
  • How can I create the proper settings to fire up the API under /api and at the same time use IdServer to protect this api?

Update

Adding ValidationMode=ValidationMode.ValidationEndpoint, fixed my problem, thanks to Scott Brady

Thanks

Expellant answered 7/7, 2016 at 2:49 Comment(0)
H
9

The general advice from the Identity Server team is to run any admin pages or API as a separate project (Most recent example). Best practice would be only to give your Identity Server and identity management applications access to your identity database/store.

To manage your users, yes, you could write your own API. Other options would be to contain it to a single MVC website or to use something like Identity Manager.

You can still use the same application approach however, using the OWIN map. To secure this you could use the IdentityServer3.AccessTokenValidation package, using code such as:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
    Authority = ConfigurationManager.AppSettings["idserver:stsOrigen"],
    RequiredScopes = new[] { "adminApi" },
    ValidationMode = ValidationMode.ValidationEndpoint
});
Haematozoon answered 11/7, 2016 at 8:13 Comment(9)
Hi scott when you say another project do you also mean to have in another url?, I would like to have the identity servers and api to be under the same domain but on different paths, I added the api and it's working right under /api but if I turn on the authentication using IdServer then it stops working because my guess is Owin hasn't loaded yet the idserver which causes the authority endpoint to fail, any idea?Expellant
check my question,I added the code I have for the api settingsExpellant
You can keep the same url (using different paths) just keep the code separate. You can deploy projects (think VS solution) to different paths on the same url in IIS if this applies to you. Using the AccessTokenValidation middleware in an OWIN path should be fine, if it's failing at startup then this sounds like a separate issue/question. I've seen projects use an Identity Server implementation in the same application as you are before. It does work.Haematozoon
Yes, I added my api in a different project but I can't get around the problem with the failing authority when using authenticationExpellant
thanks, adding this ValidationMode = ValidationMode.ValidationEndpoint fixed it, I can't find on github the explanation for the ValidationMode parameter, do you know any urlExpellant
I tried this, but when my Application API calls my Identity API, I'm still receiving 401 Unauthorized, even though I have a valid access token set in my HttpClient and I have set up the UseIdentityServerBearerTokenAuthentication as described in this answer. Unfortunately, my logs also do not provide me any additional information. The last entries in my log merely say that they successfully validated my token request and then successfully returned a token response. I have no clue why/where the 401 comes from. The 401 is returned before I can reach my breakpoint in my Identity Api Controller.Dacia
Identity API isn't a thing in this SO question, so I'm going to assume you are talking about the example API in the IdentityServer 4 Quickstart documentation. Either way this is a separate SO question.Haematozoon
Err.. not exactly. OP mentioned he created a Api on top of his Identity Server for managing User Data - That's exactly what I have done, and then I experienced the same problem as OP when he said he started failing authority. He says the ValidationMode.ValidationEndpoint fixed it, unfortunately this isn't working for me. When my Application API calls the "User Management" api on top of my identity server, I still get 401 even though I have a valid access token and have followed the same steps. Doesn't feel like a separate question to me, still feels relevant to this thread.Dacia
I figured it out - Your accepted answer mentions to add a call to app. UseIdentityServerBearerTokenAuthentication(), which works; however the placement of this call during the order of operations is very important. I discovered that this call needs to happen BEFORE api routing is mapped. I placed your accepted answer at the top of my Startup.Configuration() method and the 401 went away. Not sure if I missed it or what but in all of my logs (including trace) I never found any indicator as to what was causing my 401. I just got lucky in thinking Order of Operations might be the issue.Dacia

© 2022 - 2024 — McMap. All rights reserved.