API Security in C#

API Security , ANGULAR WITH CORE .NET AND MVC RAZOR ENGINE

                         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 Image
    For more detail about JWT token have a look on https://jwt.io/introduction/

    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()
            }

    When adding the authentication middleware by calling AddAuthentication, we
    configure the default authentication scheme to be Bearer. By further configuring the
    authentication, we call the AddJwtBearer function and specify JwtBearerOptions, where
    the IssuerSigningKey, ValidIssuer, and ValidAudience are assigned from the values
    sourced in the appSettings.json configuration file.
    Inside the Configure function, we need to remember to call UseAuthentication,
    which puts everything in place for the authentication flow.

    The AddAuthentication and UseAuthentication methods are called
    before AddMvc and UseMvc to handle authentication early in the pipeline.

    Have a look on below code to learn how to generate a token


    private string GenerateToken(SecurityKey key)
    {
    var now = DateTime.UtcNow;
    var issuer = Configuration["JWT:Issuer"];
    var audience = Configuration["JWT:Audience"];
    var identity = new ClaimsIdentity();
    var signingCredentials = new SigningCredentials(key,
    SecurityAlgorithms.HmacSha256);
    var handler = new JwtSecurityTokenHandler();
    var token = handler.CreateJwtSecurityToken(issuer, audience, identity,
    now, now.Add(TimeSpan.FromHours(1)), now, signingCredentials);
    var encodedJwt = handler.WriteToken(token);
    return encodedJwt;
    }


    Protecting Sensitive Data

    Sometimes it is necessary to store sensitive data, and we need a way to securely protect
    the contents thereof using a reliable and robust mechanism because storing
    the mechanism might not be as secure. The data-protection APIs provided by Windows is great for securing sensitive data on desktop applications but are not suitable for web
    applications.
    The ASP.NET Core data-protection stack offers a long-term replacement for the old
    cryptography model used in previous versions of ASP.NET and is designed to align better
    with modern security requirements out of the box.

    Have a look on below code


     public static void Main(string[] args)
            {
                var service = new ServiceCollection().AddDataProtection().Services.BuildServiceProvider();
                var protecterProvider =   service.GetService<IMyRecord>(); // Interface
                var protector = protecterProvider.CreateProtector("MyTestingPurpose");
             }


    SSL Security 

    A secure sockets layer (SSL) is a protocol for transmitting private data via
    the web. By enforcing SSL, we add a layer of security to our solution to make it less
    vulnerable to attacks.

    It is recommended to enforce SSL in the overall communication between the
    components of applications as it will reduce the risk of man-in-the-middle attacks
    (MITM) https://en.wikipedia.org/wiki/Man-in-the-middle_attack

    Have a look on below code

      public void Configure(IServiceCollection serviceDescriptors)
            {

                serviceDescriptors.Configure<MvcOptions>(x => {
                    x.Filters.Add(new RequireHttpsAttribute());
                });

     

    CORS (Cross-Origin Resource Sharing)

    Most browsers have a built-in security mechanism that prevents web pages from
    making AJAX requests to other domains that are different from the current website or
    application. This restriction is called a same-origin policy and helps to protect websites
    against malicious access to sensitive data from other sites.
    In the modern API landscape, chances of having different domains between the
    components of applications are pretty good, and sometimes there is a need to let sites
    make cross-origin domain calls to various web APIs. Cross-origin resource sharing
    (CORS) is a W3C standard that solves this problem by allowing the relaxation of the
    same-origin policy.
    By using CORS, a server can explicitly allow specific cross-origin requests, and it’s
    much safer than previous techniques were that tried to solve the cross-origin problem.
    An origin of a request is the combination of the scheme, host, and port. The following
    example endpoint URLs have identical origins:

     public void Configure(IServiceCollection serviceDescriptors, IApplicationBuilder app)
            {
                serviceDescriptors.AddCors();
                app.UseCors();
             }

    With ❤️ Happy Coding

    Comments

    Popular posts from this blog

    How to disable table row in Angular

    How to create XML file dynamically in c#.net?

    How to get Array value in Angular ?