问题
I'm new to asp.net core. I'm trying to make a small web service using jwt authentication and OpenOauth from Google , Facebook, ...
I've read this post : https://stormpath.com/blog/token-authentication-asp-net-core
This post is about authenticating with jwt in ASP.Net core, but, I also want to verify whether the user is disabled or active in my system.
My db has one table with 4 columns: Id, Name, Password, Status (0 - Disabled | 1 - Active).
How can I archieve my goal ?
Can anyone help me please?
P/S : I've searched google for complete tutorials about jwt in asp.net but there were so little. Full source code for authentication flow is appreciated.
回答1:
There are three way i tested(they worked, but i don't know which one is correct way).
First is using OnTokenValidated
event :
OnTokenValidated = async (ctx) =>
{
if(user is disabled)
{
ctx.Response.Headers.Append(
HeaderNames.WWWAuthenticate,
ctx.Options.Challenge);
ctx.SkipToNextMiddleware();
}
}
Second is using Use
method after jwt middleware:
app.Use(async (context, next) =>
{
var auth = await context.Authentication.AuthenticateAsync("Bearer");
if (auth.Identity.IsAuthenticated && user is disabled)
{
context.Response.Headers.Append(
HeaderNames.WWWAuthenticate,
"Bearer");
}
await next();
});
Last is using SecurityTokenValidators
:
public class CustomSecurityTokenValidator : JwtSecurityTokenHandler
{
public CustomSecurityTokenValidator()
{
}
public override ClaimsPrincipal ValidateToken(string securityToken,
TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
var principal = base.ValidateToken(securityToken, validationParameters, out validatedToken);
if(user is disabled)
{
throw new SecurityTokenNotYetValidException();
}
else
{
return principal;
}
}
}
..... in Startup.cs ...........
var options = new JwtBearerOptions()
{
//....
}
options.SecurityTokenValidators.Clear();
options.SecurityTokenValidators.Add(new CustomTokenValidator());
app.UseJwtBearerAuthentication(options);
来源:https://stackoverflow.com/questions/39762599/bearer-token-web-api-asp-net-core-without-redirection