Answer the question
In order to leave comments, you need to log in
How to create one api method for authorized and not authorized user in .net core 2?
Hello. in .net core it is possible to cut off unauthorized users access to methods using the Authorize attribute. But I want to make one method for both those and those, but with one condition, if the user came not authorized, I do not want to give part of the data, how can this be done in the body of the method.
Unfortunately this.User doesn't work without the Authorize attribute
Answer the question
In order to leave comments, you need to log in
solved in the following way, wrote an extension for the context
public static string GetUserId(ClaimsPrincipal user)
{
return user.FindFirst(OpenIdConnectConstants.Claims.Subject)?.Value?.Trim();
}
public static async Task<(bool IsAuth, string UserId)> GetUserId(this HttpContext conntext)
{
var auth = await conntext.AuthenticateAsync(OpenIddictValidationDefaults.AuthenticationScheme);
return (auth.Succeeded, GetUserId(auth.Principal));
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question