Я генерирую токен после того, как пользователь проверит OTP. В вашем случае вам не нужно ничего проверять.
Метод API
public async Task<IActionResult> LoginFunction(
[HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "Account/Login")] HttpRequest req, ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var accountDto = JsonConvert.DeserializeObject<AccountDto>(requestBody);
log.LogInformation($"ValidateOTP for phoneNumber {accountDto.PhoneNumber}");
var isUserValid = await this.accountService.ValidateOTP(accountDto.PhoneNumber, accountDto.OTP);
if (isUserValid)
{
return (ActionResult)new OkObjectResult(BuildToken(accountDto));
}
return (ActionResult)new NotFoundObjectResult("Invalid OTP");
}
private UserToken BuildToken(AccountDto accountDto)
{
var claims = new[]
{
new Claim(ClaimTypes.MobilePhone, accountDto.PhoneNumber)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("LKM3LKM344NKSFN4KJ345N43KJN4KJFNK")); //read from config
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
// Expiration time
var expiration = DateTime.UtcNow.AddYears(1);
JwtSecurityToken token = new JwtSecurityToken(
issuer: AppConstraint.TokenIssuer,
audience: AppConstraint.Audience,
claims: claims,
expires: expiration,
signingCredentials: creds);
return new UserToken()
{
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = expiration
};
}
Получив токен, вы можете сохранить этот токен в браузере пользователя и отправлять с каждым запросом.
Настраиваемый атрибут авторизации с использованием MrAdvice Aspect
public class AuthorizedAttribute : Attribute, IMethodAsyncAdvice
{
public async Task Advise(MethodAsyncAdviceContext context)
{
try
{
try
{
HttpRequest request = (HttpRequest)context.Arguments[0];
var tokenString = request.Headers[AppConstraint.Authorization].ToString().Split(' ')[1];
JwtSecurityToken token = new JwtSecurityTokenHandler().ReadJwtToken(tokenString);
if (token.ValidTo <= DateTime.Now)
{
throw new SecurityTokenExpiredException("Token has expired");
}
var claimPrincipal = GetIdentityFromToken(tokenString);
request.HttpContext.User = claimPrincipal;
}
catch
{
context.ReturnValue = Task.FromResult<IActionResult>((ActionResult)new UnauthorizedResult());
return;
}
await context.ProceedAsync(); // this calls the original method
}
catch
{
throw;
}
}
private ClaimsPrincipal GetIdentityFromToken(string token)
{
var tokenParams = new TokenValidationParameters()
{
RequireSignedTokens = true,
ValidAudience = AppConstraint.Audience,
ValidateAudience = true,
ValidIssuer = AppConstraint.TokenIssuer,
ValidateIssuer = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("LKM3LKM344NKSFN4KJ345N43KJN4KJFNK"))
};
var handler = new JwtSecurityTokenHandler();
var result = handler.ValidateToken(token, tokenParams, out _);
return result;
}
}
Надеюсь, это поможет сгенерировать и проверить собственный токен.