Skip to content

Commit

Permalink
JWT support roles auth #194
Browse files Browse the repository at this point in the history
  • Loading branch information
shps951023 committed Jun 12, 2024
1 parent ebca211 commit f4a3cb2
Show file tree
Hide file tree
Showing 15 changed files with 87 additions and 61 deletions.
17 changes: 12 additions & 5 deletions src/Frontend_Identity/public/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,18 @@ document.getElementById('loginForm').addEventListener('submit', function (event)

xhr.onload = function () {
if (xhr.status === 200) {
const token = JSON.parse(xhr.responseText)['X-MiniAuth-Token'];
if (token!=undefined && token!=null )
localStorage.setItem('X-MiniAuth-Token', token);

window.location.href = returnUrl;
const data = JSON.parse(xhr.responseText);
if (data.ok === false) {
document.getElementById('message').textContent = 'Login failed. Please check your credentials.';
return;
}
if (data.data.accessToken!=undefined && data.data.accessToken!=null) {
localStorage.setItem('X-MiniAuth-Token', data.data.accessToken);
}
// after 1 second then redirect to returnUrl
setTimeout(function () {
window.location.href = returnUrl;
}, 1000);
} else {
document.getElementById('message').textContent = 'Login failed. Please check your credentials.';
}
Expand Down
3 changes: 2 additions & 1 deletion src/Frontend_Identity/src/axios/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ const service = axios.create({
service.interceptors.request.use(
config => {
if (localStorage.getItem('X-MiniAuth-Token')) {
config.headers['X-MiniAuth-Token'] = localStorage.getItem('X-MiniAuth-Token');
// authorization header token = localStorage.getItem('X-MiniAuth-Token')
config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('X-MiniAuth-Token');
}
showLoading();
return config;
Expand Down
60 changes: 28 additions & 32 deletions src/MiniAuth.IdentityAuth/MiniAuthIdentityEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
using MiniAuth.IdentityAuth.Models;
using System;
using System.Collections.Concurrent;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -76,37 +77,43 @@ TDbContext _dbContext
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
// Payload issuer



var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Name, user.UserName)
};
//var userRoles = _dbContext.UserRoles.Where(w => w.UserId == user.Id).Select(s => s.RoleId).ToArray();
// get userRoles Name
var userRoles = _dbContext.UserRoles.Where(w => w.UserId == user.Id).Select(s => s.RoleId).ToArray();
foreach (var userRole in userRoles)
var rolesName = _dbContext.Roles.Where(w => userRoles.Contains(w.Id)).Select(s => s.Name).ToArray();
foreach (var item in rolesName)
claims.Add(new Claim(ClaimTypes.Role, item));
claims.Add(new Claim("sub", user.UserName));


var secretkey = MiniAuthOptions.IssuerSigningKey;
var credentials = new SigningCredentials(secretkey, SecurityAlgorithms.HmacSha256);
var tokenDescriptor = new SecurityTokenDescriptor()
{
claims.Add(new Claim(ClaimTypes.Role, userRole));
}
var jwtToken = new JwtSecurityTokenHandler().WriteToken(CreateToken(claims, MiniAuthOptions.TokenExpiresIn));
Subject = new ClaimsIdentity(claims),
Expires = DateTime.UtcNow.AddSeconds(MiniAuthOptions.TokenExpiresIn),
Issuer = MiniAuthOptions.Issuer,
SigningCredentials = credentials

};
var tokenHandler = new JwtSecurityTokenHandler();
var tokenJwt = tokenHandler.CreateToken(tokenDescriptor);
var token = tokenHandler.WriteToken(tokenJwt);
var result = new
{
tokenType = "Bearer",
accessToken = jwtToken,
accessToken = token,
expiresIn = MiniAuthOptions.TokenExpiresIn,
//refreshToken = refreshToken
};
/*
e.g.
{
"ok": true,
"code": 200,
"message": null,
"data": {
"tokenType": "Bearer",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MTgxMTkzMzh9.I-tm9436GEXyETgUSzL7KeX5RvyN8X_4rLAKLDMZnZk",
"expiresIn": 900
}
}
*/

await OkResult(context, result.ToJson());
return;
Expand Down Expand Up @@ -492,17 +499,6 @@ TDbContext _dbContext
}
}
}
private JwtSecurityToken CreateToken(List<Claim> claims,int expires)
{
var secretkey = MiniAuthOptions.IssuerSigningKey;
var credentials = new SigningCredentials(secretkey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
expires: DateTime.Now.AddSeconds(expires),
signingCredentials: credentials
);

return token;
}
private static string GetNewPassword()
{
return $"{Guid.NewGuid().ToString().Substring(0, 10).ToUpper()}@{Guid.NewGuid().ToString().Substring(0, 5)}";
Expand Down
12 changes: 6 additions & 6 deletions src/MiniAuth.IdentityAuth/MiniAuthIdentityServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,22 +88,22 @@ public static IServiceCollection AddMiniAuth<TDbContext, TIdentityUser, TIdentit
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

})
//.AddJwtBearer()
.AddJwtBearer(options =>
{
options.IncludeErrorDetails = true;
options.IncludeErrorDetails = true;

options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier",
RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
ValidateIssuer = true,
ValidIssuer = "User",
ValidIssuer = MiniAuthOptions.Issuer,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = false,
IssuerSigningKey =MiniAuth.MiniAuthOptions.IssuerSigningKey
IssuerSigningKey = MiniAuth.MiniAuthOptions.IssuerSigningKey
};
});
})
;
}
}
else
Expand Down
1 change: 1 addition & 0 deletions src/MiniAuth.IdentityAuth/MiniAuthOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,6 @@ public enum AuthType
/// Seconds
/// </summary>
public static int TokenExpiresIn = 15*60;
public static string Issuer = "MiniAuth";
}
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit f4a3cb2

Please sign in to comment.