.netangularasp.net-coreasp.net-apicontroller

Asp.Net Core + Angular = Protect Api without login


I have a .net core + angular application that doesn't have login functionality. I don't need login but i want to have an "admin panel" type functionality.

For example I want to add posts to my site.

I understand that I can't use API / addpost / myPassword or whatever complex string known only by me because there are ways to see that. How can I protect my API without implementing register/ login functionality?


Solution

  • There are couple of things you can do.

    The easiest thing you can do is create a custom ActionFilterAttribute that will validate your service call before entering your API controller method.

    I've used a Guid value here, but you can use anything.

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class CustomValidateRequestAttribute : ActionFilterAttribute
    {
    
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
                var headerValue = actionContext.Request.Headers.FirstOrDefault(item => item.Key == "validation-value").Value?.FirstOrDefault();
                Guid guidValidationValue;
    
                if (string.IsNullOrWhiteSpace(headerValue ) && !Guid.TryParse(headerValue , out guidValidationValue))
                {
                    throw new UnauthorizedAccessException();
                }
    
                base.OnActionExecuting(actionContext);
            }
        }
    

    You will add this custom attribute to your AddPost method in your API controller.

    [HttpPost]
    [CustomValidateRequest]
    public async Task<IHttpActionResult> AddPost...//rest of your code
    

    In your service on the client side, you will have to add this header value to headers. Something like:

    addPosts(url, data) {
        let headers = new Headers();
        headers.append('validation-value', 'your-guid-value-or-something-else');
        return this.http.post(url, {
          headers: headers
        });
      }
    

    For a more complicated and more secure options, you can check out how to implement Anti-Forgery Middleware here and here.