As we all know, in Webapi, if you have an interface that requires permissions, you will typically plug a field with permissions into the header. However, in the document download interface with permissions, we cannot set header information, either by post or by Get mode. Distress? Don't worry, we'll slowly dismantle and analyze the steps.
A document download interface with permissions is generally divided into 3 steps:
1, verify the authority;
2. Find data and generate document or document flow;
3. Write the document to the response stream and return to the client.
The first step, we will not talk about, you can use authentication permissions of the middleware, such as Identity4, to do the function of authorization authentication.
The key lies in the second and third steps.
We can separate the second step and the third step in the interface, divided into two interfaces to complete the download function of a document.
The second step is detailed in the following ways:
1, the front-end using the Post method, the need to download the parameters to the backend, and the field with permission to plug into the header;
2, the backend received the message, the first to determine the permissions, that is, whether the current user has the right to download the document or data;
3, the permission verification does not pass, then returns the error to the front end;
4. After permission validation is passed, the data is queried and the document is generated to disk. If the document is downloaded directly, you can omit this step;;
5. Get the file name and current time parameters of the document, symmetric encryption with a key, and return the encrypted string to the front end.
The method in the second step of the FAQ:
1, using post mode transmission, and set header information;
2. Why do I need to encrypt the current time together? We can use this time to determine if the URL is out of date. The expiration time can be customized, generally set to between 30 seconds to 120 seconds.
The detailed method for the third step is as follows:
1, the front end will return the second step of the encrypted string through post or get to the backend;
2, the back end through the key resolution to get the file name and a time;
3, through the current time minus the time after decryption, determine whether the current encryption string is expired;
4, if it has expired, return the error message to the front;
5. If it is not expired, the document stream is loaded and returned to the front end.
Through the above method, we implemented the document download operation with permission in Webapi.
. NET core Webapi file Download method with permissions