-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #2329 from sky1045/feature/jwt
Introduce JWT Authentication for GraphQL(Optional)
- Loading branch information
Showing
8 changed files
with
146 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
NineChronicles.Headless/Middleware/JwtAuthenticationMiddleware.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
using System; | ||
using System.IdentityModel.Tokens.Jwt; | ||
using System.Linq; | ||
using System.Security.Claims; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Primitives; | ||
using Microsoft.IdentityModel.Tokens; | ||
using Newtonsoft.Json; | ||
using Serilog; | ||
|
||
namespace NineChronicles.Headless.Middleware; | ||
|
||
public class JwtAuthenticationMiddleware : IMiddleware | ||
{ | ||
private readonly ILogger _logger; | ||
private readonly JwtSecurityTokenHandler _tokenHandler = new JwtSecurityTokenHandler(); | ||
private readonly TokenValidationParameters _validationParams; | ||
|
||
public JwtAuthenticationMiddleware(IConfiguration configuration) | ||
{ | ||
_logger = Log.Logger.ForContext<JwtAuthenticationMiddleware>(); | ||
var jwtConfig = configuration.GetSection("Jwt"); | ||
var issuer = jwtConfig["Issuer"] ?? ""; | ||
var key = jwtConfig["Key"] ?? ""; | ||
_validationParams = new TokenValidationParameters | ||
{ | ||
ValidateIssuer = true, | ||
ValidateAudience = false, | ||
ValidateLifetime = true, | ||
ValidateIssuerSigningKey = true, | ||
ValidIssuer = issuer, | ||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(key.PadRight(512 / 8, '\0'))) | ||
}; | ||
} | ||
|
||
public async Task InvokeAsync(HttpContext context, RequestDelegate next) | ||
{ | ||
context.Request.Headers.TryGetValue("Authorization", out var authorization); | ||
if (authorization.Count > 0) | ||
{ | ||
try | ||
{ | ||
var (scheme, token) = ExtractSchemeAndToken(authorization); | ||
if (scheme == "Bearer") | ||
{ | ||
ValidateTokenAndAddClaims(context, token); | ||
} | ||
} | ||
catch (Exception e) | ||
{ | ||
_logger.Error($"Authorization error {e.Message}"); | ||
context.Response.StatusCode = 401; | ||
context.Response.ContentType = "application/json"; | ||
await context.Response.WriteAsync( | ||
JsonConvert.SerializeObject( | ||
new { errpr = e.Message } | ||
)); | ||
return; | ||
} | ||
} | ||
await next(context); | ||
} | ||
|
||
private (string scheme, string token) ExtractSchemeAndToken(StringValues authorizationHeader) | ||
{ | ||
var headerValues = authorizationHeader[0].Split(" "); | ||
if (headerValues.Length < 2) | ||
{ | ||
throw new ArgumentException("Invalid Authorization header format."); | ||
} | ||
|
||
return (headerValues[0], headerValues[1]); | ||
} | ||
|
||
private void ValidateTokenAndAddClaims(HttpContext context, string token) | ||
{ | ||
_tokenHandler.ValidateToken(token, _validationParams, out SecurityToken validatedToken); | ||
var jwt = (JwtSecurityToken)validatedToken; | ||
var claims = jwt.Claims.Select(claim => new Claim(claim.Type, claim.Value)); | ||
context.User.AddIdentity(new ClaimsIdentity(claims)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
namespace NineChronicles.Headless.Properties; | ||
|
||
public class JwtOptions | ||
{ | ||
public bool EnableJwtAuthentication { get; } | ||
|
||
public string Key { get; } = ""; | ||
|
||
public string Issuer { get; } = "planetariumhq.com"; | ||
} |