Comments (7)
You could always create your own IAuthorizationEvaluator and register it with the IOC container.
public class JwtTokenAuthorizationEvaluator : IAuthorizationEvaluator
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IHostingEnvironment _environment;
private readonly AuthorizationSettings _authorizationSettings;
public JwtTokenAuthorizationEvaluator(IHttpContextAccessor httpContextAccessor,
IHostingEnvironment environment,
AuthorizationSettings authorizationSettings)
{
_httpContextAccessor = httpContextAccessor;
_environment = environment;
_authorizationSettings = authorizationSettings;
}
public async Task<AuthorizationResult> Evaluate(ClaimsPrincipal principal, object userContext, Dictionary<string, object> arguments, IEnumerable<string> requiredPolicies)
{
var cxt = userContext as GraphQLUserContext;
ClaimsPrincipal claimsPrincipal = _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated ? _httpContextAccessor.HttpContext.User : null;
if (claimsPrincipal == null)
{
var response = await _httpContextAccessor.HttpContext.AuthenticateAsync();
if (response.Succeeded)
{
claimsPrincipal = response.Principal;
_httpContextAccessor.HttpContext.User = response.Principal;
}
else
{
return AuthorizationResult.Fail(SuperEnumerable.Produce(response.Failure.Message));
}
}
var context = new AuthorizationContext();
context.User = claimsPrincipal;
context.UserContext = userContext;
context.Arguments = arguments;
var authPolicies = _authorizationSettings.GetPolicies(requiredPolicies);
var tasks = new List<Task>();
authPolicies.Apply(p =>
{
p.Requirements.Apply(r =>
{
var task = r.Authorize(context);
tasks.Add(task);
});
});
await Task.WhenAll(tasks.ToArray());
return !context.HasErrors
? AuthorizationResult.Success()
: AuthorizationResult.Fail(context.Errors);
}
from authorization.
/// <summary>
/// Defines a GraphQL user context.
/// </summary>
[ExcludeFromCodeCoverage]
public class GraphQLUserContext : IProvideClaimsPrincipal
{
/// <summary>
/// Gets or sets the user.
/// </summary>
/// <value>
/// The user.
/// </value>
public ClaimsPrincipal User { get; set; }
}
public static void AddAuthorization( this IServiceCollection services){
.AddUserContextBuilder(httpContext =>
{
if (httpContext.User.Identity.IsAuthenticated)
{
return new GraphQLUserContext { User = httpContext.User };
}
else
{
var result = httpContext.AuthenticateAsync().GetAwaiter().GetResult();
if (result.Succeeded)
{
httpContext.User = result.Principal;
}
return new GraphQLUserContext { User = result.Principal };
}
});
/// <summary>
/// Sets a default level of security for all types.
/// </summary>
/// <typeparam name="TSourceType">The type of the source type.</typeparam>
[ExcludeFromCodeCoverage]
public class SecureObjectGraphType<TSourceType> : ObjectGraphType<TSourceType>
{
/// <summary>
/// Initializes a new instance of the <see cref="SecureObjectGraphType{TSourceType}"/> class.
/// </summary>
public SecureObjectGraphType()
{
this.AuthorizeWith("DefaultPolicy");
}
}
///
[ExcludeFromCodeCoverage]
public class MyGraphQLType : SecureObjectGraphType<GraphQLEntity>
{
public MyGraphQLType(){
//you can only access this field if you are have "MyPolicy".
Field(x => x.SecureField, true).AuthorizeWith("MyPolicy");
Field(x => x.Name, true))
}
}
}
from authorization.
I believe I am experiencing a similar roadblock.
Startup.cs
services.AddGraphQLAuth(options => {
options.AddPolicy("AdminPolicy", p => {
p.RequireClaim(ClaimTypes.Role, "admin");
});
});
services.AddGraphQL(options =>
{
options.EnableMetrics = true;
options.ExposeExceptions = true;
})
.AddUserContextBuilder(httpContext =>
{
return new GraphQLUserContext { User = httpContext.User };
});
services.AddMvc();
setting a breakpoint on return new GraphQLUserContext { User = httpContext.User };
reveals that my custom claim has been added (via middleware), yet GraphiQL reports the error
"message": "GraphQL.Validation.ValidationError: You are not authorized to run this query.\nRequired claim 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role' with any value of 'admin' is not present.",
from authorization.
@tulde23 do you have any example with JWT bearer auth? for authorize and anonymous request with different graphql queries
from authorization.
@tulde23 Thank you, I have used the JwtTokenAuthorizationEvaluator and it is handing the authenticated and anonymous graphql queries as well
from authorization.
Very similarly to the above approach, you can also use:
IAuthorizationRequirement
from authorization.
Closed as outdated.
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
- ClaimsPrincipal not retrived trying to use AuthorizeWith in GraphQL queries HOT 6
- 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.