API Security in C#
Security Implementation in API
Having APIs everywhere is excellent, but they need to be secure externally as well as
internally. Even a small breach has the potential risk of a damaging ripple effect. API
security is not limited to authentication or authorization but also includes protecting
the underlying infrastructure, like rate limiting to prevent denial of service (dos) or
distributed denial of service (DDoS) attacks. Attackers continuously come up with new and creative ways to breach systems, and it’s important to keep on standard and up-to-date
with the latest threats out there.
ASP.NET Core offers a wide range of features to help us configure and manage
the security of our APIs. The framework provides a rich identity model for securing
applications and integrates with third-party identity providers like Facebook or Twitter,
as well as offers a mechanism to manage application secrets for communicating with
these providers.
we will learn the basics of what authentication and authorization are
by clearly understanding the differences between them as well as ways of implementing
them in our API applications. We will learn about the ASP.NET Core data-protection
stack for storing sensitive data securely and how to enforce secure communication by
using a secure sockets layer (SSL).
CORS
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served. A web page may freely embed cross-origin images, stylesheets, scripts, iframes, and videos.
Authentication and Authorization
Authentication is the process of verifying the identity of the person or system requesting access to a specific resource, and authorization is the process of verifying if the authenticated user has the sufficient
rights to do certain things. Think of authentication as the right one has to enter a room,
while authorization dictates what one can do once in the room.
The authentication process can be abstracted away from the application and
used by other services as well, but the authorization process is typically specific to an
application, where specific roles have different permissions.
In short, Authentication is the process of validating user and Authorization means how many parts you can use after validating your access.
Have a look on below Image
The above image gives us a clear idea about Authentication. Firs request is anonymous request hence it should return 401 status code to the client , the second request is authorized user with basic authentication hence it is a valid user ( We should validate request on the server using credential). therefor server will 200 status code to the client
The server can provide multiple authentication schemes that the client can choose
from for authenticating them. as per above image, we see that the server
is using the Basic authentication scheme. Here are some other authentication schemes
- Although the Anonymous scheme cannot be classified as an authentication scheme, it is still an empty scheme that does not contain any authentication information. It is mainly used to grant access to everyone.
The Basic authentication scheme is one of the oldest and previously most commonly used schemes for authenticating users as it provides a simple authentication flow. This scheme requires a string that consists out of a username and password concatenated with a colon (:), and then encoded as a Base64 string. For example, a typical Authorization header containing a Basic authentication scheme with username ****** and password as ********** look like this -
Authorization : dGhpcyBpcyAgdXNlcm5hbWUgYW5kIHBhc3N3b3JkCg==
- The Digest authentication scheme is a replacement for the Basic authentication scheme. The server sends a random string to the client as a challenge. This random string is called a nonce. The client authenticates them by sending a hash that contains a username, password, and nonce, as well as potentially other information.
- Bearer authentication is among the most popular and more secure authentication schemes around. It works by making use of bearer tokens for accessing OAuth 2.0–protected resources. Anyone in possession of a bearer token can gain access to associated resources. Bearer tokens are usually short-lived and expire after a specific point
- The NTLM authentication scheme is short for NT LAN Manager and is a challenge-response scheme that is more secure than the Digest scheme. This scheme uses Windows credentials to transform to challenge data, instead of using the encoded credentials.
- The Negotiate scheme automatically selects between the NTLM authentication scheme and the Kerberos protocol, which is faster than NTLM.
Now that we have a broader understanding of authentication, authorization, and
the surrounding technologies, let’s implement security on an API by using the Bearer
authentication scheme. For this implementation, we will make use of JSON Web Tokens
(JWTs), which is an open and industry standard for representing claims between parties.
The JWT standard provides a compact and self-contained way to transfer
information between two parties as a JSON object. JWTs are signed with an HMAC secret
or an RSA public and private key pair. A JWT consists of three parts, namely a header, a
payload, and a signature, and is rendered using the following pseudocode:
[X=base64(header)].[Y=base64(payload)].[sign([X].[Y])]
The resulting JWT token is a string consisting of the three parts separated by a dot (.).
The first two parts are Base64-encoded strings of the header and payload sections in the
JSON object and the last part is a combination of the first two Base64 strings, separated
by a dot (.) and signed.
Have a look on below ImageFor more detail about JWT token have a look on https://jwt.io/introduction/
Now that we have a broader understanding of authentication, authorization, and
the surrounding technologies, let’s implement security on an API by using the Bearer
authentication scheme. For this implementation, we will make use of JSON Web Tokens
(JWTs), which is an open and industry standard for representing claims between parties.
The JWT standard provides a compact and self-contained way to transfer
information between two parties as a JSON object. JWTs are signed with an HMAC secret
or an RSA public and private key pair. A JWT consists of three parts, namely a header, a
payload, and a signature, and is rendered using the following pseudocode:
[X=base64(header)].[Y=base64(payload)].[sign([X].[Y])]
The resulting JWT token is a string consisting of the three parts separated by a dot (.).
The first two parts are Base64-encoded strings of the header and payload sections in the
JSON object and the last part is a combination of the first two Base64 strings, separated
by a dot (.) and signed.
have a look on below code where we are using middleware to authenticate a request
// We need to install JWP from Nuget (JwtBearerDefaults)
serviceDescriptors.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var serverSecret = new SymmetricSecurityKey(Encoding.UTF8.
GetBytes(Configuration["JWT:ServerSecret"]));
options.TokenValidationParameters = new
TokenValidationParameters
{
IssuerSigningKey = serverSecret,
ValidIssuer = Configuration["JWT:Issuer"],
ValidAudience = Configuration["JWT:Audience"]
};
});
public void Configure(IServiceCollection serviceDescriptors, IApplicationBuilder app)
{
app.UseAuthentication()
}
Comments
Post a Comment