简体   繁体   中英

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 i can protect my api without implementing register/ login functionality?

Thanks!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM