Code Monkey home page Code Monkey logo

Comments (6)

xaberue avatar xaberue commented on June 20, 2024 1

Hi @joemcbride !!

Thanks a lot for your quick reply

In relation to point 1: All endopoints will require authentication, so I can imagine that it would be better to protect the whole schema right? By the moment I was only testing with one query.

Then, regarding point 2 and 4 are ok currently.

I will take a look to point 3, because it is true, my project is currently using the Middleware from GraphQL server.

Thanks a lot, I will revert once I'm able to tackle again

from authorization.

joemcbride avatar joemcbride commented on June 20, 2024
  1. This is probably because ASP.NET is not trying to authenticate the JWT before hitting the GraphQL endpoint/middleware. Does your API always require authentication, or are some queries allowed for anonymous users?

  2. Do you have Authentication wired up in services for JWT?

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme);
app.UseAuthentication();

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs=visual-studio#configure-identity-services
https://www.tektutorialshub.com/asp-net-core/authentication-in-asp-net-core/

  1. It looks like you're using the GraphQL Server project which uses Middleware. If some queries do not require authentication, then you will probably have to write your own middleware to run before the GraphQL middleware to "challenge" the token if it exists.
app.Use(async (context, next) =>
{
    // check for token in headers of the request found on HttpContext (context.Request)
    await context.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme);
    await next.Invoke();
});

https://www.tektutorialshub.com/asp-net-core/authentication-in-asp-net-core/

  1. Make sure your GraphQLUserContext implement the IProvideClaimsPrincipal interface.

from authorization.

xaberue avatar xaberue commented on June 20, 2024

Hi @joemcbride !!

First of all, let me apreciate your help with this topic, thanks a lot! And sorry for my late reply, I am involved in several projects and POC's...

I have checked your points, but is still not working, let me five some additional info point by point:

  1. As commented, at the end all will require auth, so I checked using AuthorizeWith both in some queries and at first. In both I have same result, not retrieving Identity info:
this.AuthorizeWith("AdminPolicy");

Field<ListGraphType<UserModel>>(
        "all", resolve: context => _modelRepository.FromAll().ToList()
    );
  1. Yes, but not in the same way, however I checked with a REST controller and the token is properly retrieved from the same UI and the claims and roles are there.
   
services
    .AddAuthentication(opt =>
    {
        opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(opt =>
    {
        opt.SaveToken = true;
        opt.RequireHttpsMetadata = true;
        opt.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidAudience = authSettings.SiteName,
            ValidIssuer = authSettings.SiteName,
            IssuerSigningKey = SecurityKeyHelper.GetSecurityKey(privateKey)
        };
    });

services
    .AddAuthorization(x => x.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
        .Build());
  1. Yes indeed. I checked your proposal and the link provided, but I'm not sure if something else is missing or I'm not understading something... this is the code as written now:
if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();

    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "ChustaSoft Profiler V1");
        c.RoutePrefix = string.Empty;
    });

    app.UseHsts();
    app.UseHttpsRedirection();
}

app.UseRouting();
app.UseCors(CORS_POLICY_NAME);

app.Use(async (context, next) =>
{
    await context.ChallengeAsync(JwtBearerDefaults.AuthenticationScheme);
    await next.Invoke();
});
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

app.UseGraphQL<UserSchema>("/api/users");
app.UseGraphQL<ApplicationSchema>("/api/applications");

app.UseGraphQLPlayground(new PlaygroundOptions { GraphQLEndPoint = "/api/users" }, "/ui/users");
app.UseGraphQLPlayground(new PlaygroundOptions { GraphQLEndPoint = "/api/applications" }, "/ui/applications");
  1. Yes it is:
public class GraphQLUserContext : Dictionary<string, object>, IProvideClaimsPrincipal
{
    private ClaimsPrincipal user;

    /// <inheritdoc />
    public ClaimsPrincipal User { get => user; set => user = value; }
}

Do you have an idea of what else is missing or not working properly?

Many many thanks in advance :)

from authorization.

ViRuSTriNiTy avatar ViRuSTriNiTy commented on June 20, 2024

I was struggling with an empty ClaimsPrinicipal for the last 8 hours also. I think what is missing is this:

services.AddGraphQLAuthorization(options =>
{
    options.AddPolicy(YourPolicyName, p =>
    {
        // use authentication schemes configured in Startup.cs
        p.AddAuthenticationSchemes(options.DefaultPolicy.AuthenticationSchemes.ToArray());

        p.RequireAuthenticatedUser();
    });
})

app.UseEndpoints(endpoints =>
{
	endpoints.MapGraphQL<YourSchema>().RequireAuthorization(YourPolicyName);
});

Hope this helps.

from authorization.

sungam3r avatar sungam3r commented on June 20, 2024

@Xelit3 Did you solve this problem? Maybe you mixed APIs from different projects? We have this one for general-purpose auth and another one for ASP.NET Core.

from authorization.

sungam3r avatar sungam3r commented on June 20, 2024

Reopen if you have any questions.

from authorization.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.