简体   繁体   中英

How to create a wrapper/middleware to all actions in controllers to decrypt incoming requests

The reason for the wrapper is to decrypt all incoming requests from clients, encryption/decryption was done to make Net Core Api not easily available. I don't like the fact that everybody can access my Net Core API and have seen a number of attempts to parse my data.

Therefore, I decided to create only one Controller that receives encrypted GET/POST requests with the name of Controller and Action. The decryption/encryption logic works fine but that problem is that I need to always create a new condition to the root controller to identify passed names of actions and controllers

Could you please advise if it is possible to create a wrapper
1) Catch a request
2) Decrypt its request object
3) Pass the request to the action/controller to which it belongs to

Giving more details:

This is my RootController with one Process action (All interactions with clients are done via this root controller, the rest controllers are available only for admins)

[HttpPost]
[Route("")]
public ActionResult Process([FromBody] RootRequest request)
{
    //Here I am checking what controller and actions was 
    if (request.c.ToLower() == "news" && request.a.ToLower() == "getnews")
    {
        var newsCtrl = new NewsController();
        var decrypted = DecryptRequest(request.r);
        var reqObject = (NewsRequest)decrypted;
        //return this.RedirectToAction<NewsController>(m => m.GetNews());
        return newsCtrl.GetNews(reqObject);
    }
}

This is my request object:

public class RootRequest {
    // Endpoint
    public string a { get; set; }
    // Contoller
    public string c { get; set; }
    // Request
    public object r { get; set; }
    // Key
    public string k { get; set; }
}

I want to avoid creating this kind of checks:

if (request.c.ToLower() == "news" && request.a.ToLower() == "getnews")

and create an intermediate wrapper that could only decrypt the request and pass the request further

What you're doing is creating a coding nightmare. This will become massively unmanagable the more it grows. The correct way to handle this is to use some sort of authentication (JWT) that will prevent unauthorised access. You dont want to be obscuring data for valid consumers just to prevent access. Take a look at this for more details on JWT: https://jasonwatmore.com/post/2018/08/14/aspnet-core-21-jwt-authentication-tutorial-with-example-api

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