M
M
Maxim Melnikov2019-05-29 16:08:39
.NET
Maxim Melnikov, 2019-05-29 16:08:39

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

1 answer(s)
M
Maxim Melnikov, 2019-05-29
@MrPhelko

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));
        }

and call it in the method

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question