Use OAuth Jwt Net Core 7
Install JwtBearer
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Create Secret Key
"Jwt":{
"SecretKey": "124asfdqr3124123412qrqwerfqwer"
}
Generate Token
static string GenerateToken(IEnumerable claims, string secretKey){
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
SymmetricSecurityKey securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey));
SigningCredentials credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
JwtSecurityToken token = new JwtSecurityToken(issuer: "cse.net.vn", audience: "cse.net.vn", claims: claims, signingCredentials: credentials, expires: DateTime.Now.AddSeconds(20));
return handler.WriteToken(token);
}
Authentication Jwt
string secretKey = builder.Configuration.GetValue<string>("Jwt:SecretKey") ?? "";
builder.Services.AddAuthentication(p => {
p.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
p.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(p => {
p.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
ValidIssuer = "cse.net.vn",
ValidAudience = "cse.net.vn",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
});
Fresh token
static string RefreshToken(string accessToken, string secretKey){
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
TokenValidationParameters parameters = new TokenValidationParameters{
ValidIssuer = "cse.net.vn",
ValidAudience = "cse.net.vn",
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)),
ValidateLifetime = false
};
ClaimsPrincipal principal = handler.ValidateToken(accessToken, parameters, out SecurityToken token);
if(principal != null && token != null && token is JwtSecurityToken jwtSecurity && jwtSecurity.Header.Alg.Equals(SecurityAlgorithms.HmacSha256Signature)){
return GenerateToken(principal.Claims, secretKey);
}
throw new SecurityTokenException("Token Invalid");
}
Api Sign In
[HttpPost("login")]
public string? Login(LoginModel obj){
if(obj.U.StartsWith("thanh") && obj.P.Equals("123")){
List<Claim> claims = new List<Claim>{
new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.Name, obj.U)
};
return GenerateToken(claims, secretKey);
}
return null;
}
Api Refresh token
[HttpPost("refresh")]
public string? Refresh(Token obj){
return RefreshToken(obj.AccessToken, secretKey);
}
Client Sign In
Member Repository
public class MemberRepository{
static Uri baseUri = new Uri("cse.net.vn");
public async Task<string?> Login(LoginModel obj){
using (HttpClient client = new HttpClient()){
obj.Password = Helper.HashString(obj.Password);
client.BaseAddress = baseUri;
HttpResponseMessage message = await client.PostAsJsonAsync("/api/auth/login", obj);
if (message.IsSuccessStatusCode){
return await message.Content.ReadAsStringAsync();
}
return null;
}
}
[HttpPost]
public async Task<IActionResult> SignIn(LoginModel obj){
string? token = await repository.Login(obj);
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
var securityToken = handler.ReadJwtToken(token);
ClaimsIdentity identity = new ClaimsIdentity(securityToken.Claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(new ClaimsPrincipal(identity), new AuthenticationProperties{
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(30),
IsPersistent = obj.Remember
});
}
Client Request Access Token
public class MemberRepository{
public async Task<IEnumerable<Member>?> GetMembers(string totken){
using (HttpClient client = new HttpClient()){
client.BaseAddress = baseUri;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", totken);
return await client.GetFromJsonAsync<IEnumerable<Member>>("/api/auth/login");
}
}