0

I am trying to add basic authorization to .NET Core Web API. For this purpose, I added this class

  namespace BasicAuthentication
  public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
        {
            public override void OnAuthorization(HttpActionContext actionContext) {
                base.OnAuthorization(actionContext);
                if (actionContext.Request.Headers.Authorization != null)
                {
                    var authToken = actionContext.Request.Headers
                        .Authorization.Parameter;
                    var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
                    var arrUserNameandPassword = decodeauthToken.Split(':');
                    if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
                    {
                        Thread.CurrentPrincipal = new GenericPrincipal(
                         new GenericIdentity(arrUserNameandPassword[0]), null);
                    }
                    else
                    {
                        actionContext.Response = actionContext.Request
                        .CreateResponse(HttpStatusCode.Unauthorized);
                    }
                }
                else
                {
                    actionContext.Response = actionContext.Request
                     .CreateResponse(HttpStatusCode.Unauthorized);
                }
            }
    
            public static bool IsAuthorizedUser(string Username, string Password)
            {
                
                return Username == "test" && Password == "test123";
            }
        }

Then, I added annotation to a controller method:

    [BasicAuthentication]
    [HttpGet]
    public IEnumerable<Visit> Get()
    {
        var visit = tourActivityExpenseContext.Visits
                        .Include(e => e.ExpenseDetails)
                        .ToList();
        return visit;
    }

But, I can still consume the API via postman without the authorization credentials. Am I missing something here?

2
  • Did you add the filter in your Startup.cs file? Here's a similar answer:stackoverflow.com/a/44127671 Commented Jul 4, 2022 at 2:18
  • And this question may also help? Commented Jul 4, 2022 at 2:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.