1
votes

Using .Net Core 2.1 and Identity Server 4

I have 3 startups one for IS4, MVC App, and API App. I am able to log into my MVC application fine, and retrieve my access_token. I try to access the API with this token and am unable to authorize the request.

This is my IS4 Startup.cs localhost:5000

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<IdentityContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        services.Configure<IISOptions>(iis =>
        {
            iis.AuthenticationDisplayName = "Windows";
            iis.AutomaticAuthentication = false;
        });

        services.AddIdentityServer()
            .AddAspNetIdentity<ApplicationUser>()
            .AddConfigurationStore(configDb =>
            {
                configDb.ConfigureDbContext = db => db.UseNpgsql(Configuration.GetConnectionString("IdentityServer4ConfigurationContext"),
                    sql => sql.MigrationsAssembly(typeof(IdentityServer4Startup).GetTypeInfo().Assembly.GetName().Name));
            })
            .AddOperationalStore(operationDb =>
            {
                operationDb.ConfigureDbContext = db => db.UseNpgsql(Configuration.GetConnectionString("IdentityServer4PersistedGrantContext"),
                     sql => sql.MigrationsAssembly(typeof(IdentityServer4Startup).GetTypeInfo().Assembly.GetName().Name));
            })
            .AddDeveloperSigningCredential();

My MVC Startup.cs localhost:61000

services.AddMvc();

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<IdentityContext>()
            .AddDefaultTokenProviders();

        services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
                {
                    options.SignInScheme = "Cookies";
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    options.ClientId = "mvc";
                    options.ClientSecret = "secret";
                    options.ResponseType = "code id_token";
                    options.SaveTokens = true;
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.Scope.Add("api1");
                    options.Scope.Add("offline_access");
                    options.Scope.Add("openid");
                    options.Scope.Add("email");
                });

And my API Startup.cs localhost:62000

services.AddMvc();


        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "oidc";
        })
            .AddIdentityServerAuthentication("oidc", options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                options.ApiName = "api1";
            });

my Client info is

new Client {
                ClientId = "mvc",
                ClientName = "Example Mvc",
                AllowedGrantTypes = GrantTypes.Hybrid,
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "role",
                    "api1"
                },
                RedirectUris = new List<string> {"http://localhost:61000/signin-oidc"},
                PostLogoutRedirectUris = new List<string> { "http://localhost:61000/signout-callback-oidc" }
            }

and API resource

new ApiResource {
                Name = "api1",
                DisplayName = "Custom API",
                Description = "Custom API Access",
                UserClaims = new List<string> {"role"},
                ApiSecrets = new List<Secret> {new Secret("scopeSecret".Sha256())},
                Scopes = new List<Scope> {
                    new Scope("api1"),
                }
            }

Whenever I try to call the API while logged in as my Client I cannot access it. It will either give the error

[10:40:11 ERR] Invalid redirect_uri: http://localhost:62000/signin-oidc
{
  "ClientId": "mvc",
  "ClientName": "MVC Client",
  "AllowedRedirectUris": [
    "http://localhost:61000/signin-oidc"
  ],
  "SubjectId": "anonymous",
  "RequestedScopes": "",
  "Raw": {
    "client_id": "mvc",
    "redirect_uri": "http://localhost:62000/signin-oidc",
    "response_type": "code id_token",
    "scope": "openid profile api1 offline_access email",
    "response_mode": "form_post",
    "nonce": "636778932114224044.N2M1YzZhMjktMThjMS00ZGEyLWI1OGQtZjM1YmZiMzViNDVkNDQ2NDhjZWMtNzk4Mi00NTc2LWI2YzctNjAwMzkwNjI5NGE5",
    "state": "CfDJ8EzT-5PsjT5Htj2FYGOkFvxTH4w-8q3uXGtc1wXYyvWMHyarfbV0cQz8cFh4ESIW33n4pwtIEmLhrTpX-0Y0-_HS24cWs05nR3npx1ZIAJsYr9hIqB9hj9Ic_QYkU2Z_bcjjnaynqfbF5KIyyQhYGNlDxDfknwZUTXpPzTFEhLTcnam7O-b-xV9a3e9iWARoFZRBLjGV5Hs5i-8jS5EGM9DpqwcvrUjSUlRVDP-TzBBhYPhswn2hKsjkhL26_Gp9lluoKNLOvUVM-yq1zHbbI9uTcZzS_2GtbQoPuuGTmCuOoV-c-K2IztzXP88W-osYaY9wQP2qi8aXD951hrAhYbo",
    "x-client-SKU": "ID_NETSTANDARD1_4",
    "x-client-ver": "5.2.0.0"
  }
}

I don't believe I need to have the redirect_uri registered. But I tried it anyway and when I do the same request it will just return the login screen. Because it could not authenticate my request.

Here is the HttpClient request I am sending to the API from the MVC

var apiUrl = "http://localhost:62000/test/api";
        var authenticate = await HttpContext.AuthenticateAsync("Cookies");
        var accessToken = authenticate.Ticket.Properties.GetTokenValue("access_token");
        var client = new HttpClient();
        client.SetBearerToken(accessToken);
        var response = await client.GetAsync(apiUrl);
        return Json(response.Content.ReadAsStringAsync());

From all of the examples and documents I cannot see why this is not working. Any help would be appreciated.

Here is the output of IS4 when I try to call the API with the bearer token.

[12:38:58 INF] Request starting HTTP/1.1 GET http://localhost:5000/connect/authorize?client_id=mvc&redirect_uri=http%3A%2F%2Flocalhost%3A62000%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20api1%20offline_access%20email&response_mode=form_post&nonce=636779003387253889.MThjYjQ5MzItOTY3NS00NmM1LWJhZDItMzkxMzYyMWQzZTUwZThjNThmMjUtMmQyZC00M2YyLTk3OTktN2E3OTc1ZDcyNmM0&state=CfDJ8EzT-5PsjT5Htj2FYGOkFvzm1YFOhTLHlbLS3LpJd_xUBgDz8hWjGkXxSzfnWKqoVU5d4L7ESHCSDGxqmxqnMh1-j-IUGBLzt5uEYFi2M4QV6WmGN1Lv5bMkUDRbrE9pdCNc7vLDUDZY1OWlp4HfQ0vEMr8-OfUH4Q00fOn1v9zpcE6QlHI5Aye9xiFOshHRyMCNwEEcVrLz4Y06Hsa-40OKom3xb8sie09JtiSMZJL9WyKgKYGRgqUIpD6wqryBafzMl_t1tvegYWESq59TafnIpvrFd3ifdOzJx6cXul4ZCcFv0wfvsqpUgCF7t7xyMSwtheDSiE2AySkbnrpr_Dg&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0
[12:38:58 INF] Invoking IdentityServer endpoint: IdentityServer4.Endpoints.AuthorizeEndpoint for /connect/authorize
[12:38:58 INF] ValidatedAuthorizeRequest
{
  "ClientId": "mvc",
  "ClientName": "MVC Client",
  "RedirectUri": "http://localhost:62000/signin-oidc",
  "AllowedRedirectUris": [
    "http://localhost:62000/signin-oidc",
    "http://localhost:61000/signin-oidc"
  ],
  "SubjectId": "anonymous",
  "ResponseType": "code id_token",
  "ResponseMode": "form_post",
  "GrantType": "hybrid",
  "RequestedScopes": "openid profile api1 offline_access email",
  "State": "CfDJ8EzT-5PsjT5Htj2FYGOkFvzm1YFOhTLHlbLS3LpJd_xUBgDz8hWjGkXxSzfnWKqoVU5d4L7ESHCSDGxqmxqnMh1-j-IUGBLzt5uEYFi2M4QV6WmGN1Lv5bMkUDRbrE9pdCNc7vLDUDZY1OWlp4HfQ0vEMr8-OfUH4Q00fOn1v9zpcE6QlHI5Aye9xiFOshHRyMCNwEEcVrLz4Y06Hsa-40OKom3xb8sie09JtiSMZJL9WyKgKYGRgqUIpD6wqryBafzMl_t1tvegYWESq59TafnIpvrFd3ifdOzJx6cXul4ZCcFv0wfvsqpUgCF7t7xyMSwtheDSiE2AySkbnrpr_Dg",
  "Nonce": "636779003387253889.MThjYjQ5MzItOTY3NS00NmM1LWJhZDItMzkxMzYyMWQzZTUwZThjNThmMjUtMmQyZC00M2YyLTk3OTktN2E3OTc1ZDcyNmM0",
  "Raw": {
    "client_id": "mvc",
    "redirect_uri": "http://localhost:62000/signin-oidc",
    "response_type": "code id_token",
    "scope": "openid profile api1 offline_access email",
    "response_mode": "form_post",
    "nonce": "636779003387253889.MThjYjQ5MzItOTY3NS00NmM1LWJhZDItMzkxMzYyMWQzZTUwZThjNThmMjUtMmQyZC00M2YyLTk3OTktN2E3OTc1ZDcyNmM0",
    "state": "CfDJ8EzT-5PsjT5Htj2FYGOkFvzm1YFOhTLHlbLS3LpJd_xUBgDz8hWjGkXxSzfnWKqoVU5d4L7ESHCSDGxqmxqnMh1-j-IUGBLzt5uEYFi2M4QV6WmGN1Lv5bMkUDRbrE9pdCNc7vLDUDZY1OWlp4HfQ0vEMr8-OfUH4Q00fOn1v9zpcE6QlHI5Aye9xiFOshHRyMCNwEEcVrLz4Y06Hsa-40OKom3xb8sie09JtiSMZJL9WyKgKYGRgqUIpD6wqryBafzMl_t1tvegYWESq59TafnIpvrFd3ifdOzJx6cXul4ZCcFv0wfvsqpUgCF7t7xyMSwtheDSiE2AySkbnrpr_Dg",
    "x-client-SKU": "ID_NETSTANDARD1_4",
    "x-client-ver": "5.2.0.0"
  }
}
[12:38:58 INF] Showing login: User is not authenticated
[12:38:58 INF] Request finished in 138.5606ms 302
[12:38:58 INF] Request starting HTTP/1.1 GET http://localhost:5000/account/login?returnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dmvc%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A62000%252Fsignin-oidc%26response_type%3Dcode%2520id_token%26scope%3Dopenid%2520profile%2520api1%2520offline_access%2520email%26response_mode%3Dform_post%26nonce%3D636779003387253889.MThjYjQ5MzItOTY3NS00NmM1LWJhZDItMzkxMzYyMWQzZTUwZThjNThmMjUtMmQyZC00M2YyLTk3OTktN2E3OTc1ZDcyNmM0%26state%3DCfDJ8EzT-5PsjT5Htj2FYGOkFvzm1YFOhTLHlbLS3LpJd_xUBgDz8hWjGkXxSzfnWKqoVU5d4L7ESHCSDGxqmxqnMh1-j-IUGBLzt5uEYFi2M4QV6WmGN1Lv5bMkUDRbrE9pdCNc7vLDUDZY1OWlp4HfQ0vEMr8-OfUH4Q00fOn1v9zpcE6QlHI5Aye9xiFOshHRyMCNwEEcVrLz4Y06Hsa-40OKom3xb8sie09JtiSMZJL9WyKgKYGRgqUIpD6wqryBafzMl_t1tvegYWESq59TafnIpvrFd3ifdOzJx6cXul4ZCcFv0wfvsqpUgCF7t7xyMSwtheDSiE2AySkbnrpr_Dg%26x-client-SKU%3DID_NETSTANDARD1_4%26x-client-ver%3D5.2.0.0
[12:38:58 INF] Route matched with {action = "Login", controller = "Account"}. Executing action ASC.ADEX.Runtime.Controllers.AccountController.Login (ASC.ADEX.Runtime)
[12:38:58 INF] Executing action method ASC.ADEX.Runtime.Controllers.AccountController.Login (ASC.ADEX.Runtime) with arguments (["/connect/authorize/callback?client_id=mvc&redirect_uri=http%3A%2F%2Flocalhost%3A62000%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20api1%20offline_access%20email&response_mode=form_post&nonce=636779003387253889.MThjYjQ5MzItOTY3NS00NmM1LWJhZDItMzkxMzYyMWQzZTUwZThjNThmMjUtMmQyZC00M2YyLTk3OTktN2E3OTc1ZDcyNmM0&state=CfDJ8EzT-5PsjT5Htj2FYGOkFvzm1YFOhTLHlbLS3LpJd_xUBgDz8hWjGkXxSzfnWKqoVU5d4L7ESHCSDGxqmxqnMh1-j-IUGBLzt5uEYFi2M4QV6WmGN1Lv5bMkUDRbrE9pdCNc7vLDUDZY1OWlp4HfQ0vEMr8-OfUH4Q00fOn1v9zpcE6QlHI5Aye9xiFOshHRyMCNwEEcVrLz4Y06Hsa-40OKom3xb8sie09JtiSMZJL9WyKgKYGRgqUIpD6wqryBafzMl_t1tvegYWESq59TafnIpvrFd3ifdOzJx6cXul4ZCcFv0wfvsqpUgCF7t7xyMSwtheDSiE2AySkbnrpr_Dg&x-client-SKU=ID_NETSTANDARD1_4&x-client-ver=5.2.0.0"]) - Validation state: Valid
[12:38:58 INF] Executed action method ASC.ADEX.Runtime.Controllers.AccountController.Login (ASC.ADEX.Runtime), returned result Microsoft.AspNetCore.Mvc.ViewResult in 41.3848ms.
[12:38:58 INF] Executing ViewResult, running view Login.
[12:38:58 INF] Executed ViewResult - view Login executed in 1.8018ms.
[12:38:58 INF] Executed action ASC.ADEX.Runtime.Controllers.AccountController.Login (ASC.ADEX.Runtime) in 78.939ms
[12:38:58 INF] Request finished in 83.6512ms 200 text/html; charset=utf-8
2

2 Answers

1
votes

I set up my API authentication using AddJwtBearer as shown below. And I see you use AddIdentityServerAuthentication. May be that's the reason?

services.AddJwtBearer(o =>
               {
                   o.Authority = "<id-server>";
                   o.Audience = "<api-audience>";
                   o.RequireHttpsMetadata = true;
               });

And the API controllers have the AuthenticationSchemes specified as shown below:

[Route("api/rates")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class RatesController : Controller
{
}
1
votes

You typically only get Invalid redirect_uri when the Client - i.e. your MVC app - is redirecting to the Identity Server so that a user can authenticate, not when calling the API, nor caused by the API itself, so you should remove the challenge from the API's config and leave that to the UI only. Your API also needs its secret for some back-channel calls to the Identity Server, so change your API's Startup.cs to this:

        services.AddAuthorization();
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(
                options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.ApiName = "api1";
                    options.ApiSecret = "scopeSecret";
                    options.RequireHttpsMetadata = false;

                    // You will almost certainly want these at some point too,
                    // to prevent the API talking to the IS for every
                    // API call.  Adjust the duration as desired.
                    options.EnableCaching = true;
                    options.CacheDuration = TimeSpan.FromMinutes(10);
                });

You don't show the Configure() part of your API's Startup.cs, but ensure it has

.UseAuthentication();

before the call to

.AddMvc()

Now you should just need to decorate the protected API methods with [Authorize] and ensure you pass through the user's bearer token to calls to those API methods.