Auth in Web API 2 (edit)
Bài viết này nhằm hướng dẫn cách sử dụng Token Based Authentication và cách kiểm tra đầu vào cho dữ liệu POST lên API.
Auth in Web API 2 (Guideline)
Usually what you do is implement the login logic in that method, and return a token which will be then validated on each call to your api.
http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
Enable CORS
http://bitoftech.net/2014/03/05/new-asp-net-web-api-2-ihttpactionresult-cors-tutorial/
Tools
- Identity
- Cross Origin Resource Sharing (CORS)
- Swagger
RESTful API là gì?
RESTful API often use GET (read), POST (create), PUT (replace/update) and DELETE (to delete a record)
Here are the 5 basic design guidelines that make a RESTful API:
- Resources (URIs)
- HTTP methods
- HTTP headers
- Query parameters
- HTTP Status Codes
HTTP Status Codes
It is important to consider numerous REST API status return codes, and not just using 404 for errors and 200 for success.
I wrote about those codes already but I think it is worth mentioning again that other codes should be considered:
- 400 bad request - for when the validation did not pass.
- 401 unauthorized - When authorization of the user has failed, like incorrect username or password.
- 403 forbidden - This status is mostly for Authentication and Data Access Rights. It should indicate the user, that he does not have access to a specific resource in the API.
- 405 method not allowed - In case you do not support a method (like PATCH or DELETE for example).
- 429 too many requests - Can be used to signal that too many requests came from the same origin.
The Top 7 REST API Security Threats
1. Injection Attacks
In an injection attack, a dangerous code is embedded into an unsecured software program to stage an attack, most notably SQL injection and cross-site scripting. This exposure could, in fact, be manipulated by transferring untrusted data into the API as part of a query or command. The input is subsequently implemented by the interpreter which can result in an attacker obtaining unauthorized access to information or carry out other damages.
The most effective way to stop or deny an injection attack is by adding input validation, here are the most crucial guidelines:
- Validate input: length/range/format and type
- Achieve an implicit input parameters validation by using strong types like numbers, booleans, dates, times or fixed data ranges in API parameters
- Constrain string inputs with regex
- Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large
2. DoS Attacks
In a Denial of Service (DoS) attack, the attacker in most cases pushes enormous messages requesting the server or network to establish requests consisting of invalid return addresses. The attack is capable of rendering a RESTful API into a non-functional situation if the appropriate security precautions are not adopted. In recent times, whether your API is exposed or not, it could possibly be accessible by other people (attackers inclusive).
As these API DoS attacks become more common, and as organizations increasingly rely on APIs for their business needs, security professionals should proactively plan to deal with such attacks. Even if an API key (or access token) used for application authentication is disabled, a key can easily be reacquired through a standard browser request. Therefore, invalidating a current access token is not a long-term solution. If a DoS attack is traced back to a specific IP address, then blacklisting that IP address isn't a long-term solution either, because the attacker can easily acquire a new one.
That's why multiple access control methods are necessary. For non-sensitive information, the use of API keys might be sufficient. However, to better prevent a DoS attack, the use of HTTPS and more robust authentication mechanisms, including OAuth, mutual (two-way) TLS (transport layer security) authentication, or SAML (security assertion markup language) tokens, are necessary.
To prevent a massive amount of API requests that can cause a DDoS attack or other misuses of the API service, apply a limit to the number of requests in a given time interval for each API (also called spike arrest). When the rate is exceeded, block access from the API key at least temporarily, and return the 429 (too many requests) HTTP error code.
In case you are starting to build your new REST API, check for web servers that have many security-oriented features.
3. Broken Authentication
These particular problems can make an attacker to either bypass or take control of the authentication methods made use of by a web program. Missing or inadequate authentication can result in attack whereby JSON web tokens, API keys, passwords, etc. can be compromised. The aim of the attack is usually to take charge of several accounts, not to mention the attacker getting the equal privileges as the attacked user. Solely authenticated users should be given access to the APIs.
The APIs authorization and authentication requirements could very well be taken care of using OpenId/OAuth tokens, PKI, API key. It would be wise never to send credentials over connections that are not encrusted, also don’t reveal session ID in the Web URL.
4. Sensitive Data Exposure
Exposure of sensitive data caused by lack of encryption in transit or at rest may result in an attack. Sensitive Data Exposure happens whenever an application is unable to properly secure sensitive data. The information can differ from private health information to credit card information, session tokens, passwords and a lot more tend to be venerable to attack. Sensitive data requires high security which includes encryption at rest or in transit, in addition to extraordinary safe practices when exchanged with the browser.
In order to avoid exposing sensitive data, you must use an SSL.
Today, you can get a free certificate with Let's Encrypt. SSL and TLS go a long way in removing basic API vulnerabilities with almost minimal effort.
To get an excellent report on how good your implementation is, run your URL against the Qualys SSL server test.
5. Broken Access Control
Access control, in some cases known as authorization, is how a web software allows access to functions and contents to certain people rather than everybody. Missing or inadequate access control can permit the attacker to gain control of other users accounts, alter access privileges, change data etc.
Company application access tends to attack when operational level accessibility is not configured properly by developers leading to access vulnerabilities. Declined access is the best-known consequence of broken access controls and exploitation of access control is the main craft of attackers.
Access control is detectable making use of manual means, or even via automation for the lack of access controls in some frameworks. Access control is usually productive if implemented in reliable server-less or server-side API, whereby the attacker won't be able to alter the access control metadata.
6. Parameter Tampering
It’s an attack that is based on the manipulation of parameters exchanged between client and server in order to modify application data, such as user credentials and permissions, price and quantity of products, etc. Usually, this information is stored in cookies, hidden form fields, or URL query strings and is used to increase application functionality and control.
This happens when a harmful website, program, instant message, blog, or e-mail makes a user’s internet browser to carry out an unnecessary action on an authorized site. It allows an attacker to makes the targeted system to carry out a function using the target's web browser, unknowingly to the attacked user, perhaps until the not authorized transaction has been carried out.
The attack success depends on integrity and logic validation mechanism errors, and its exploitation can result in other consequences including XSS, SQL Injection, file inclusion, and path disclosure attacks.
You should carefully validate URL parameters received to ensure the data represents a valid request from the user. Invalid requests can be used to attack the API directly or targeting the application and systems behind the API. Put validators on the application and try to use API Signing for the requests sent to the REST API. It is also good to create automatic security tests for your API in order to see that no parameter tampering affects your REST API.
7. Man-In-The-Middle-Attack (MITM)
It’s when an attacker is secretly altering, intercepting, or relaying communications between two interacting systems and intercepts the private and confidential data passed between them. MITM attacks occur in two stages: interception and decryption.
HTTP and Lack of TLS
The absence of a Transport Layer Security (TLS) in an API is practically equivalent to handing out open invitations to hackers. Transport layer encryption is one of the most elementary ‘must-haves’ in a secure API. Unless a TLS is used, risks of the fairly common ‘Man-In-The-Middle’ attacks remain very high. Use both SSL and TLS in your APIs, especially if you are going public with your APIs.