Showing posts with label Web API. Show all posts
Showing posts with label Web API. Show all posts

Saturday, April 5, 2025

Web API | Json Web Token - JWT

Creating JWT -

  1. Import “Microsoft.AspNetCore.Authentication.JwtBearer” package from Nuget. 
  2. Select the algorithm. like HMACSHA256. 
  3. Creating the claims collection. Remember there are standard claims and you can add your own. 
  4. Create credentials object using algo and secret key.
  5. Generate token using claims and credentials.
  6. Add [Authorize] attribute to controller, then action methods of this controller will be authorized. 
JWT token has this format: Header.payload.signature
Header: Contains algorithm used to create JWT like HSA256
Payload: Contains information related to user and authentication
Signature: Created using Header and payload

JWT is encoded not encrypted, so never put critical information in it.



Validating JWT at Application


Validating JWT token in middleware



Refresh Token: This is sent by server along with jwt, when jwt expired client sends this refresh token to server and server generate new JWT and refresh token and sends to client.
Benefit of refresh token is that again and again client no need to send user credentials.

Storing JWT at client end:
In-memory: Using the application variable we can store the token when the application is running. this is for application session only.
Cookie: If you want to store beyond application session(log time). cookie is a good place.
Indexed DB, Session storage and local storage are prone to XSS attacks.
Create cookie using HTTP only. By doing so this cookie can not be read using JavaScript “document.cookie”. In other words cookie is safe from XSS attacks.


Below could be third party Google, amazon, facebook or self owned services -

Open Id: Used for authentication, you want to just know if the user exists in the system in or not. Like shopping sites , mobile applications , single sign on etc. 
OAUTH: Used for authorization, when third party application tries to access resources. 
Open ID Connect: Used for authentication plus authorization both, when you want to authenticate and authorize as well like intranet websites.

Identity Server: This is a free open source server that you can use to implement Open Id Connect and Auth. It is certified by OpenId Foundation.
Single Sign on: Organizations those use single sign on, they redirects requests to their Identity server from each of their web portals, user get authenticated get token from Identity server and can access the web portals.
Identity server could a third party like Okta.


Web API | Roles Vs Claims

 



Web API Facts

Web Api is REST based service on web works on http or https.

REST - Representational State Transfer 

Facts 

Rest Facts

  1. Client-Server model: Its client server model but there is no coupling, completely decoupled model.
  2. Statelessness: Web API is rest based service, is request has complete information to serve, there is no state management.
  3. Catchability: Data can be cached for better performance.
  4. Layered system: There might be multiple layers at service end, client doesn't need to care about it. When client calling an endpoint, that might be an intermediate endpoint.
  5. Uniform Interface - 
    • Unique identification
    • Resource manipulation through representation
    • Self descriptive message


Facts About Web API

  1. Web API controller inherit ControllerBase class while MVC controller inherits Controller class.
  2. Web API returns only data while MVC controller can return view or partial view as well.
  3. What is content Negotiation?
    Web API can return data format based on "Accept" request header.


  4. Web API Vs WCF



WCF Rest Vs WA Rest: Web API built for Rest only from start, while Rest is added with WCF later.

.Net Core | Web API Basics

Web API is REST based web service.

Why Web API?
  1. Reuse logic for internal application
  2. Reuse logic for external application
  3. Separation of concerns
  4. Security 
  5. Environment of multiple teams 

*DI is not only limited to controllers, any class implements injected interface can use them.
*Web application and Web API both can use same classes in .Net Core.

Some Facts to be noted about ASP.Net Core Web API:
  1. Attribute Routing: Actions automatically called without mentioning action name as routes mentioned above actions.

    [Route("api/[controller]")]
        [ApiController]
        public class ValuesController : ControllerBase
        {
            // GET api/values
            [HttpGet]
            public ActionResult<IEnumerable<string>> Get()
            {
                return new string[] { "value1", "value2" };
            }

            // GET api/values/5
            [HttpGet("{id}")]
            public ActionResult<string> Get(int id)
            {
                return "value";
            }

            // POST api/values
            [HttpPost]
            public void Post([FromBody] string value)
            {
            }

            // PUT api/values/5
            [HttpPut("{id}")]
            public void Put(int id, [FromBody] string value)
            {
            }

            // DELETE api/values/5
            [HttpDelete("{id}")]
            public void Delete(int id)
            {
            }
        }
     
  2. Automatic Model validation: Posted model validated automatically no need to write any code. In case of any issue in validation, it returns with 400.
  3. Binding Source Attributes: 
    1. [FromBody]
    2. [FromForm]
    3. [FromQuery]
    4. [FromHeader]
    5. [FromRoute]
    6. [FromServices]

      // POST api/values
      [HttpPost]
      public void Post([FromBody] string value)
      {
      }
  4. Core Web API supports only Json in response, even if you request some other format type in request header.

    If you want to use XML format in request and response than 
    • You need to install below package from nuget.
      Microsoft.ASPNetCore.Mvc.Formatters.xml
    • Add AddXmlSerializerFormatters() method with AddMvc()
      public void ConfigureServices(IServiceCollection services)
              {
                  services.AddMvc()
                      .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
                      .AddXmlSerializerFormatters();
              } 
  5. HttpClient is the class to call and use WebAPI from .Net classes.
  6. Calling WebAPI using client side script

    Add a new item

    function addItem() {
      const item = {
        name: $("#add-name").val(),
        isComplete: false
      };

      $.ajax({
        type: "POST",
        accepts: "application/json",
        url: uri,
        contentType: "application/json",
        data: JSON.stringify(item),
        error: function(jqXHR, textStatus, errorThrown) {
          alert("Something went wrong!");
        },
        success: function(result) {
          getData();
          $("#add-name").val("");
        }
      });
    }

    Update an exiting item 
    $.ajax({
      url: uri + "/" + $("#edit-id").val(),
      type: "PUT",
      accepts: "application/json",
      contentType: "application/json",
      data: JSON.stringify(item),
      success: function(result) {
        getData();
      }
    });

    Delete an item
    $.ajax({
      url: uri + "/" + id,
      type: "DELETE",
      success: function(result) {
        getData();
      }
    });

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...