Comments (6)
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.
-
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?
-
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/
- 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/
- Make sure your
GraphQLUserContext
implement theIProvideClaimsPrincipal
interface.
from authorization.
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:
- 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()
);
- 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());
- 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");
- 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.
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.
@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.
Reopen if you have any questions.
from authorization.
Related Issues (20)
- Checking for a valid JWT and integrating with a Refresh-Token-Workflow HOT 10
- UNAUTHENTICATED error code HOT 3
- In AuthorizationValidationRule.cs the method CheckAuth is called multiple times. Why? HOT 4
- ETA for v4? HOT 18
- IAuthorizationRequirement is not sent the same variable names as those in IResolveField context HOT 2
- Any example for schema first auth example? HOT 2
- How to get a status code 401 when not authorized HOT 6
- Move GraphQLAuthExtensions from Harness into new package HOT 6
- Add docs about IAuthorizationSkipCondition and DI
- Method 'ValidateAsync' in type 'GraphQL.Authorization.AuthorizationValidationRule' from assembly 'GraphQL.Authorization, Version=4.0.0.0 HOT 7
- Question: AuthorizeWithPolicy is being ignored HOT 10
- GraphQL .net authorization with JWT token HOT 7
- AddGraphQLAuth no longer works after switching to Middleware HOT 1
- Return 401 and 403 status code HOT 5
- Is this library still relevant with GraphQL 7+ HOT 22
- How to read graphql query from authorization requirement ?
- Graphql Authorization not working HOT 4
- Faulty reference HOT 6
- How to login user and return token and id ? HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from authorization.