Search code examples
asp.net-coreasp.net-identityidentityserver4

API is authorized without the Authorization Headers in Request using Identity Server 4 and .net core Identity


I am making the API call after the successfully login through Identity server from my vue application (SPA).

Firstly i was adding the Access token in the Header and it was Authorize but i was not getting the claim. Which i have the separate Question on SO, and now i tried by removing the access token from the header during API call the application is still being Authorized.

I don't understand how i should solve the problem.

service.interceptors.request.use(config => {
  return authService
    .getToken()
    .then(tokenResponse => {
      app.$Progress.start();
      //config.headers.Authorization = `Bearer ${tokenResponse}`; removed Token
      return Promise.resolve(config);
    })
    .catch(error => {
      app.prototype.$Progress.fail();
      alert("error");
    });
});

Oidc Client Manager

export default {
    authority: "https://localhost:44305",
    client_id: "js",
    redirect_uri: `${domain}/authredirect`,
    response_type: "id_token token",
    scope:"openid profile email api1 role",
    post_logout_redirect_uri : `${domain}`,
    silent_redirect_uri: `${domain}/silent`,
}

Identity Server Client Configuration

new Client

    {
        ClientId = "js",
        ClientName = "JavaScript Client",
        AllowedGrantTypes = GrantTypes.Implicit,
        AllowAccessTokensViaBrowser = true,
        AlwaysIncludeUserClaimsInIdToken = true,
        RedirectUris =            new List<string> {"http://localhost:8080/silent","http://localhost:8080/authredirect"},
        PostLogoutRedirectUris =   { "http://localhost:8080" },
        AllowedCorsOrigins =     { "http://localhost:8080" },

        AllowedScopes =
        {
            IdentityServerConstants.StandardScopes.OpenId,
            IdentityServerConstants.StandardScopes.Profile,
             IdentityServerConstants.StandardScopes.Email,
            "api1",
            "role"
        }
    }

API Configure Services

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvcCore().AddJsonFormatters();

    services.AddAuthorization();
    services.AddCors(options =>
    {
        // this defines a CORS policy called "default"
        options.AddPolicy("default", policy =>
        {
            policy.WithOrigins("http://localhost:8080")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
    });

    var connectionString = Configuration.GetConnectionString("DefaultConnection");
    services.AddDbContext<MyContext>(o => o.UseSqlServer(connectionString));
    services.AddIdentity<User, IdentityRole<Guid>>().AddEntityFrameworkStores<MyContext>().AddDefaultTokenProviders();

    // register the repository
    services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

    services.AddMvcCore().AddJsonFormatters();
}

I have added the Project on Github. Please suggest me something. Link for Project not available currently, i will add again

Image showing my Controller with [Authorize] attribute and debugging on the value for User.Identity


Solution

  • I was able to solved the problems on this.

    I was missing the DefaultChallengeScheme on my API ConfigureServices

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