Identity Server 4 API Authentication Failure










0















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









share|improve this question




























    0















    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









    share|improve this question


























      0












      0








      0








      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









      share|improve this question
















      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






      c# postgresql asp.net-core identityserver4






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 15 '18 at 17:39







      A. Hasemeyer

















      asked Nov 15 '18 at 15:46









      A. HasemeyerA. Hasemeyer

      15711




      15711






















          2 Answers
          2






          active

          oldest

          votes


















          1














          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







          share|improve this answer























          • When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

            – A. Hasemeyer
            Nov 15 '18 at 16:09











          • In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

            – k25
            Nov 15 '18 at 16:32












          • Check out this too - stackoverflow.com/a/46372426/312219

            – k25
            Nov 15 '18 at 16:35











          • k25 are you saying to add those to the API startup? Or the MVC

            – A. Hasemeyer
            Nov 15 '18 at 16:37











          • To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

            – k25
            Nov 15 '18 at 16:39


















          1














          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.






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323063%2fidentity-server-4-api-authentication-failure%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            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







            share|improve this answer























            • When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

              – A. Hasemeyer
              Nov 15 '18 at 16:09











            • In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

              – k25
              Nov 15 '18 at 16:32












            • Check out this too - stackoverflow.com/a/46372426/312219

              – k25
              Nov 15 '18 at 16:35











            • k25 are you saying to add those to the API startup? Or the MVC

              – A. Hasemeyer
              Nov 15 '18 at 16:37











            • To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

              – k25
              Nov 15 '18 at 16:39















            1














            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







            share|improve this answer























            • When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

              – A. Hasemeyer
              Nov 15 '18 at 16:09











            • In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

              – k25
              Nov 15 '18 at 16:32












            • Check out this too - stackoverflow.com/a/46372426/312219

              – k25
              Nov 15 '18 at 16:35











            • k25 are you saying to add those to the API startup? Or the MVC

              – A. Hasemeyer
              Nov 15 '18 at 16:37











            • To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

              – k25
              Nov 15 '18 at 16:39













            1












            1








            1







            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







            share|improve this answer













            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








            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 15:53









            k25k25

            242523




            242523












            • When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

              – A. Hasemeyer
              Nov 15 '18 at 16:09











            • In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

              – k25
              Nov 15 '18 at 16:32












            • Check out this too - stackoverflow.com/a/46372426/312219

              – k25
              Nov 15 '18 at 16:35











            • k25 are you saying to add those to the API startup? Or the MVC

              – A. Hasemeyer
              Nov 15 '18 at 16:37











            • To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

              – k25
              Nov 15 '18 at 16:39

















            • When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

              – A. Hasemeyer
              Nov 15 '18 at 16:09











            • In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

              – k25
              Nov 15 '18 at 16:32












            • Check out this too - stackoverflow.com/a/46372426/312219

              – k25
              Nov 15 '18 at 16:35











            • k25 are you saying to add those to the API startup? Or the MVC

              – A. Hasemeyer
              Nov 15 '18 at 16:37











            • To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

              – k25
              Nov 15 '18 at 16:39
















            When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

            – A. Hasemeyer
            Nov 15 '18 at 16:09





            When I update to that code I get the error An unhandled exception has occurred while executing the request. System.InvalidOperationException: No authentication handler is registered for the scheme 'Bearer'. The registered schemes are: Identity.Application, Identity.External, Identity.TwoFactorRememberMe, Identity.TwoFactorUserId, Cookies, oidc. Did you forget to call AddAuthentication().Add[SomeAuthHandler]("Bearer",...)?

            – A. Hasemeyer
            Nov 15 '18 at 16:09













            In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

            – k25
            Nov 15 '18 at 16:32






            In my case the projects are not just pure API projects. So I do the following - services.AddAuthentication(...) .AddCookie() .AddOpenIdConnect(...) .AddJwtBearer(...); I guess you probably removed AddAuthentication? I would suggest adding that back and following the pattern above.

            – k25
            Nov 15 '18 at 16:32














            Check out this too - stackoverflow.com/a/46372426/312219

            – k25
            Nov 15 '18 at 16:35





            Check out this too - stackoverflow.com/a/46372426/312219

            – k25
            Nov 15 '18 at 16:35













            k25 are you saying to add those to the API startup? Or the MVC

            – A. Hasemeyer
            Nov 15 '18 at 16:37





            k25 are you saying to add those to the API startup? Or the MVC

            – A. Hasemeyer
            Nov 15 '18 at 16:37













            To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

            – k25
            Nov 15 '18 at 16:39





            To the API project, you don't need the AddOpenIdConnect(..) part if its a purely API only project, but you would still need AddAuthentication(...). The stackoverflow link comment will offer some insight perhaps.

            – k25
            Nov 15 '18 at 16:39













            1














            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.






            share|improve this answer





























              1














              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.






              share|improve this answer



























                1












                1








                1







                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.






                share|improve this answer















                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.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 15 '18 at 18:40

























                answered Nov 15 '18 at 18:33









                sellotapesellotape

                5,77821721




                5,77821721



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53323063%2fidentity-server-4-api-authentication-failure%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Barbados

                    How to read a connectionString WITH PROVIDER in .NET Core?

                    Node.js Script on GitHub Pages or Amazon S3