are standart methods that allow different application or system to communicate and share data over internet or network. Are designed to be loosely coupled, meaning changes in 1 service don't impact others. They use standart protocols HTTP(S), SOAP and formats XML,JSON and architecture style REST to facilitate communication. There are 2 types of web services:
1. SOAP based services: it is a traditional web service or ASMX, ties to SOAP, meaning both: server and client must communicate using SOAP based XML messages. Run over HTTP(S) protocol, but use SOAP format, what does it mean? HTTP is just used to carry SOAP message from client to server and back again, and SOAP protocol define SOAP message structure. The message itself is wrapped in xml. Example: client send request which contains SOAP message, the request header has Content-Type: text/xml and request body has actual message with XML structure, server process message and send back response in another HTTP response which is also XML.
- SOAP: simple object access protocol, is a messaging protocol that defines how messages should be structured and exchanged between systems. It use XML format for request and response messages, is more rigid compared to REST and include additional features like WS-Security (secure communication). More complex and heavyweight. Mostly used in enterprise-level applications.
- XML: eXtensible markup language, it's format message, define set of rules for encoding, documents which is readable by both humans and machine. Commonly used in SOAP based web service, configuration files, data storage, data exchange. SOAP messages are always encoded in XML, and includes Header,Body,Service for thing like security,routing,message,methods. SOAP messages are encoded in XML, but XML is only the format. The actual transport happens via protocols like HTTP, SMTP, or TCP. HTTP(S) is the most common.
| TCP | Transmission control protocol connection is created between sender and receiver before any data sent, if an error occurs then TCP will retransmit it, provide robust error detection. Example: HTTP(S), SMTP, SSH we use when we need reliable and error checked communication |
|---|---|
| UDP | User datagram protocol is no formal connection, it is created between sender and receiver, data is sent as individual packets without ensuring that receiver is ready. Don't guarantee anything, provide basic error detection but faster than TCP as it does not involve overhead of connection setup |
~ What is WSDL(Web Service Description Language) and how accessed in SOAP?: It is a XML file define how the service can be called, what parameters it except, and what data it returns. In SOAP web service, WSDL is an XML-based language, act as a format contract between a web service and the client to understand how to communicate, describe how SOAP service works, what client need to send and receive. How works?: When web service is deployed, it creates ?wsdl file ending (http://example.com/mywebservice?wsdl), client access this URL and understand service structure, methods and data types it has, then generate client-side code to interact with SOAP service. Use tool like wsdl.exe to generate proxy classes, ultimately make request to server using generated code, it send an XML message based on structure defined in file. SOAP service check request to ensure it conform the structure in .wsdl then process request and send back SOAP response.
~ WS*-Security: adds security mechanism to SOAP messages at the message level instead of relying on transport level security like HTTPS. Commonly use XML signature and ensure that message has not been tampered during transfer and stay confidential. Uses encryption to protect message, ensure that the message comes from a trusted sender. Provide a way to include credentials directly in the SOAP message, allowing for flexible authentication. How works?:
| HEADER | The security information (digital signature, encrypted data, tokens) is placed SOAP header. This Header are processed by the web service |
| SIGNATURE | Ensure integrity and authenticity of message, the SOAP message are signed using sender's private key. The recipient verifies the signature using the sender's public key, ensuring that the message has not been altered and it comes from a trusted sender. Private key (of sender) is used for signing, Public key (of sender) is used for verifying. Example: Alice create SOAP message, sign the message with her private key, then who has a public key will know it have been signed by Alice and attach this sign to SOAP message in WS-Header. Bob verifies the signature using Alice's public key. Ensure that message is from Alice and has not been tampered. Signing = integrity + authenticity (private key sign, public key verify). |
| ENCRYPTION | Ensure confidentiality of message, the SOAP message is encrypted using the recipient's public key and only recipient can read message by decrypt their private key. Private key (of recipient) is used for decrypting, Public key (of recipient) is used for encrypting. Example: Alice take entire SOAP message (include signature), encrypts the message using Bob's public key, this ensure that only Bob who has private key can decrypt and read message. Encryption = confidentiality (public key encrypt, private key decrypt). |
HTTP: Hypertext transform protocol, is a transport protocol used to receive and send messages over the internet. RESTfull services are relies on HTTP. It has methods:
| GET |
Used to retrieve data from a web service (e.g., fetching a list of users) |
| POST |
Sends data to the web service (e.g., creating a new user). |
| PUT |
Updates existing data in the service (e.g., updating user details). |
| DELETE |
Removes data (e.g., deleting a user) |
HTTPS: Hypertext transform protocol secure is a secure version of HTTP, it use SSL/TLS (secure socket layer/ transport layer security) encryption to protect sensitive data (like payment details) is sending between client and server.
WS* vs HTTPS: While HTTPs only protect data in transit (between 2 points), if the message is routed through multiple system, it gets decrypted/encrypted at each intermediary point. On the other hand, WS* keep security inside the message itself, so it stays protected end-to-end, even intermediaries.
Examples:
//SOAP
<soap:Envelope xmlns:soap=""> //begining and end of soap
<soap:Header> //contain additional info like security, routing
</soap:Header>
<soap:Body> //actual data in here
<GetUserDetails>
<UserId>123</UserId>
</GetUserDetails>
</soap:Body>
</soap:Envelope>
//XML FORMAT
<person>
<name>Firuza Polad</name>
<age>28</age>
<isEmployed>true</isEmployed>
</person>
//MESSAGE FORMAT = how requests/responses are structured inside SOAP
<message name="GetWeatherRequest"> //Describes the messages used (input/output).
<part name="city" type="xsd:string" />
</message>
<portType name="WeatherPortType"> // Defines the operations (methods) the service supports.
<operation name="<binding name="WeatherBinding" type="tns:WeatherPortType">">
<input message="tns:GetWeatherRequest"/>
<output message="tns:GetWeatherResponse"/>
</operation>
</portType>
<binding name="WeatherBinding" type="tns:WeatherPortType"> //Specifies how the service is accessed (usually over HTTP).
..
</binding>
<service name="WeatherService"> //Contains the service endpoint information.
..
</service>
2. RESTfull based services: over a time, web service also include RESTfull services, this service use standart HTTP methods and REST architecture style to perform operation and return json/xml as response. Restfull web service is considered an API.
- REST: representational state transfer, is an architecture style that use standart HTTP methods to perform operation. It relies on HTTPS for security, stateless (each request from the client to the server must contain all information necessary to understand and process that request, the server does not store session information between different request), meaning each request from client must contain all necessary information to complete the request. Are lightweight, easy to implement, return data in format like JSON,XML,HTML etc. Usage in Web/Mobile applications due its simplicity.
- JSON:JavaScript object notation, is a lightweight message format that is easy for human to read and write, for machine to parse and generate. Used for transfer data between server and web application. Commonly used in RestFull web services, AJAX, API, config file. JSON consist of key-value pairs enclosed in curly braces {}. Client application can easily parse the JSON response and display the data in the UI. And is language independent. Data can be organized as:
| Objects | Also knows as dictionaries or maps and represented by key and value pair. |
|---|---|
| Arrays | List of values, typically enclosed with brackets []. |
| Parsing JSON | Converting a JSON string into a data structure(like object) |
|---|---|
| Serializing JSON | Converting a data structure into a JSON string for transmission or storage. |
{
"name": "Firuza Polad",
"age": 28,
"isEmployed": true,
"skills": ["JavaScript", "HTML", "CSS"], // ARRAY
"address": { // OBJECT
"street": "123 Main St",
"city": "BAKU",
"zip": "10001"
}
}
// Parsing JSON
const jsonString = '{"name": "Firuza ", "age": 28}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: Firuza
// Serializing JSON
const obj = { name: "Firuza ", age: 28};
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: '{"name":"Firuza","age":28}'
- JSON vs XML: Both formats are used for data exchange, but JSON is more popular in nowadays as we use fewer characters, structure is simpler which enable it to read and write manually, faster than XML. Ideal for mobile and web applications.
Windows Communication Foundation is a framework used for building robust web services in .NETA framework. Allow us to send data asynchronously from one end point to another endpoint. In here endpoint can be part of continuously available service hosted by IIS or it can be a service hosted in an application. There are 3 parts of WCF applications:
- WCF Service: core part of application, define BS logic and could be anything like calculating data, retrieving information from DB, process order. It has: Service contract: Specifies what operation are provided to clients Data contract: Specifies data structure that are exchanged between the service and client.
- WCF Service Host: is responsible for hosting the WCF service, like listening for incoming request, managing lifetime, provide necessary binding. Withous a Host, the service can not be accessed, it can be hosted such as IIS (international information service) which means service runs inside IIS as As application; Self-Hosting which means we can host service inside console application etc.; WAS(windows activation service) which means more advanced version of IIS and enable non-HTTP protocol like TCP.
- Service Client: is the application or service that use the WCF service, it calls the methods from service and use them, the client can be any kind of application (web,desktop,mobile) that needs to communicate with the service. The client typically uses a proxy class generated by tools,VS which acts as an intermediary to call service methods. Example: Calling GetWeather() method from proxy class which is use WeatherService (see below)
~ Fundamentals of WCF:
| Message | EndPoint | ||||||
|---|---|---|---|---|---|---|---|
| Is a communication between client and service. WCF use SOAP message (XML based) for communication by default. Message contain Header (for authentication) and Body (for actual data). | Is the access point where WCF provide its functionality to clients, like an
address where client can send request to service. Each service has at least
1 endpoint but can have multiple for different protocols. It
has 3 important parts:
|
~ When use: Suppose we have 2 clients: One of them wants to use
WebService which sends data over the network by using HTTP protocol and want reply in XML
formati
(HTTP +
XML
e.g., SOAP/REST over HTTP), the other client wants to use WebService which sends
data over the network by using TCP protocol and replying in binary format (TCP +
Binary). The problem in here is, we need to create
2 different Services for 2 different clients. WCF is solving this problem writing one single
service which can be used by 2 different clients-either they want same protocol or a
different protocol ex: basicHttpBinding → for HTTP + XML or
netTcpBinding → for TCP + Binary. We don’t define the protocol name inside the
WebService class itself, instead we configure it in the WCF configuration
(app.config/web.config) under the <endpoint> element.
Without WCF we can create simpler,lighweight approach SOAP based service which can use
ASMX. In application we choose ASP.NET Web Application (ASMX) template. But WCF offering
more features like WS-* standarts, reliable messaging
and more, so if need full SOAP features we use WCF on .NET framework. It only runs on
Windows as part of .NET framework. In application we choose WCF Service Application app from
template. If we need SOAP on cross-platform
(Windows,Linux, MacOS) but limited features we use
SoapCore
library as WCF not supported on .NET Core (now .NET5/6/7/8). SoapCore is not
typically used for client-side, is mainly used for server-side. If we want to build a
client-side service we use
ServiceModel.Http library, it allow the client-side functionality of WCF in .Net Core
but itself does not support server-side. Key terms:
ServiceContract: Interface define service's operation, using [ServiceContract] and [OperationContract] attributes
DataContract: Class define data structure used by service.[DataContract] and [DataMember]
| WCF | WebService |
|---|---|
| ServiceContract and OperationContract used for defining WCF service | WebService and WebMethod used for defining web service |
| Support HTTP(S) , TCP protocol | Support only HTTP(S) |
| Hosted on IIS , WAS or Self containing hosting | Hosted only IIS |
| Use tool to generate proxy classes | Use tool to generate proxy classes |
| Use System.Runtime.Serialization | Use Sysyem.Xml.Serialization |
application programming interface, is set of rules and protocols that define how different software app can interact with each other. It doesn’t have to involve the Web. It has 2 types, such as local APIs (e.g., a C# class library) or remote APIs (e.g., REST APIs or SOAP APIs). Local API (No Internet) means: we're writing a C# desktop app to manipulate files. We use the .NET File API provided by the framework to perform tasks ( using the File and Directory classes and streams FileStream, StreamReader, StreamWriter ) like reading, writing, or deleting files.
WEB API: is type of Remote API allow different applications communicate with each other over WEB, using HTTP(S) as protocol. Commonly used to enable web app, mobile app and other system to interact with external services and exchange data. RESTful APIs (which use JSON or XML over HTTP) and GraphQL APIs are types of Web APIs. ASP.NET Web API (or just Web API) Used to build RESTful services. NOTE: All Web APIs are APIs, but not all APIs are Web APIs.
How works: Client using application (web, mobile) to request to webAPI, this request typically follow a URL structure and include any necessary parameters (query string, request body). Server hosting API request, interact with , perform operation and return response back to client, usually in JSON/XML formats. And client process and display this format response.
API vs WebService: Both are designed for communication over web. All Web Services are Web APIs, but not all Web APIs are Web Services.
| Web Service | Web API |
|---|---|
| Is a specific type of webAPI, are older, traditionally using SOAP (XML) or sometimes REST. e.g: Bank A wants to send transaction to Bank B and they need strong security and guaranteed message delivery. They use SOAP where message sent as XML over HTTP. Structure of message is complex with header/body/token and ensure validated before transaction is completed. Web services are stateless so we can't maintain user sessions in web services | Include all type , RestApi/ Soap Web Service/ GraphqlApi. Are modern. e.g: we are building a mobile app, we need to get weather , so application make HTTP GET request to Restfull WebAPI and receive data as JSON, response is simple and perfect for mobile application that need real-time weather update. |
What is the use of Accept and Content-Type Headers in HTTP Request? : These are important headers in Restful web services, defining format and type of data which is sent between client and server.
application/json → For JSON data.application/xml → For XML data.text/html → For HTML data.text/plain → For plain text.
POST /api/users HTTP/1.1
Content-Type: application/json
{
"name": "FS",
"email": "firuza@example.com"
}
What are the main return types supported in Web API? :different return types are supported based on the kind of response you want to send to the client.
using HttpClient client = new HttpClient();
var response = await client.GetAsync("https://url"); //or HttpResponseMessage response = ...
string content = await response.Content.ReadAsStringAsync();
HttpResponseHeaders headers = response.Headers;
if (response.IsSuccessStatusCode){
// Success logic
}
response.EnsureSuccessStatusCode(); // Throws an exception if status code is not 2xx
What is HttpClient? : is used to send HTTP request and receive HTTP response, we can use single HttpClient instance for mutliple requests. It is under System.Http.Net namespace. Use method of HTTP and works with HttpResponse. Support async programming, has methods:
Full example:
public class ApiService
{
//private readonly HttpClient _httpClient;
private readonly IHttpClientFactory _httpClientFactory;
public ApiService(IHttpClientFactory httpClientFactory)
{
//_httpClient=httpClientFactory.CreateClient();
_httpClientFactory = (IHttpClientFactory)httpClientFactory.CreateClient();
}
public async Task<string> GetDataAsync()
{
//var client = _httpClientFactory.CreateClient("FactoryClient"); IF WE HAVE SERVICE CONFIG
//HttpResponseMessage responseMessage = await client.GetAsync("/repos/weather");
var client = _httpClientFactory.CreateClient();
HttpResponseMessage responseMessage = await client.GetAsync("https://api.example.com/");
if (!responseMessage.IsSuccessStatusCode)
{
responseMessage.EnsureSuccessStatusCode();
}
var content = await responseMessage.Content.ReadAsStringAsync();
return content;
}
public async Task<HttpResponseMessage> SendDataAsync(object data)
{
var client = _httpClientFactory.CreateClient();
data = "{\"name\":\"Firuza\"},{\"age\":\"27\"}";
var content = new StringContent
(
JsonConvert.SerializeObject(data),
Encoding.ASCII,
"application/json"
);
HttpResponseMessage responseMessage = await client.PostAsync("https://api.example.com/", content);
if (!responseMessage.IsSuccessStatusCode)
{
responseMessage.EnsureSuccessStatusCode();
}
return responseMessage;
}
}
IActionResult<T>: represent return type of action method in a class in ASP.NET Core. Part of MVC and used to response back to client. it is a base class, and derived type of ActionResult represent spesific type of HttpResponses. Common derived types:
public IActionResult MyAction() { return Ok(); }
public IActionResult MyAction() {
var data = new { Name = "Firuza", Age = 30 };
return Ok(data);
}
public JsonResult MyAction() {
var data = new { Name = "Firuza", Age = 30 };
return new JsonResult(data);
}
public IActionResult GetUser(int id){
var user=_service.getUserById(id);
if(user is null){ return NotFound(); //404 }
return Ok(user);
}
public IActionResult CreateUser(User userDTO){
if(user is null || string.IsNullOrEmpty(userDTO.name)){return BadRequest(); //400}
_service.createUser(user);
return Ok();
}
public IActionResult Dashboard(){
if(!User.IsInRole("Admin")){ return Forbid(); //401}
var data=_service.GetData();
return Ok(data);
}
public IActionResult GetText(){
var content="hello";
return new ContentResult{
Content=content;
ContentType=text/plain;
StatusCode=200;
}
}
public IActionResult Custom(){
return StatusCode(500,"internal server error");
}
return Redirect("https://anotherURL.com");
return RedirectToAction("Index");
What is HttpClient / IHttpClientFactory class?
Which of the following Open-source libraries is used by WEB API for JSON serialization? the primary one is Newtonsoft.JSON also known as Json.Net. it provide robust functionality for converting .NET object to JSON format. Ideal for complex scenarious.
class Person {
string Name {get;set;}
string Job {get;set;}
}
Person student=new Person {Name="F", Job="Dev"}
string json=JsonConvert.SerializeObject(student);
var obj=JsonConvert.DeseralizeObject<Person>(json);
System.Text.Json is fast and doesn't use much computer memory, used for modern applications.
string json=JsonSerializer.Serialize(student);
var obj=JsonSerializer.DeSerialize(string);
NetJSON is lightweight, faster than both Newtonsoft and Text.Json. But not widely known as other.
string json=NetJSON.Serialize(student);
var obj=NetJSON.Desiralize<Person>(json);
Conclusion:
JSON.stringfy() is js method used in client-side. Above methods used for servvice-side. It converts object into JSON string. used to comm with server.
const obj = { name: "Firuza", age: 28 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"Firuza","age":28}
What is ASP.NET Web API routing? : is the process of directing incoming HTTP request to appropriate controller action based on request's URL and HTTP method.
[Route("{id:int}")]
Example:
[ApiController]
[Route("api/controller")]
public class ProductsController : ApiController
{
[HttpGet("{id}")]
public IHttpActionResult GetById() { // }
[HttpGet(Name="GetAll")]
public IHttpActionResult GetAllProducts() { // }
[HttpGet("name={name}", Name="GetName")]
public IHttpActionResult GetName(string name) { // }
}
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Examples:
api/products - get all productsapi/products/5 - product with ID=5How to secure ASP.NET Web API?
Also known as Swagger, standard form of defining RestfulAPI, describe structure of API, including endpoints, request/response formats, AUTH methods and other metadata. It helps to interact with API without reading large documentation. It uses JSON format. There are various tools working with OpenAPI like Postman.
After Install-Package Swashbuckle.AspNetCore we add
services.AddSwaggerGen();
to register swagger configuration. Then use below code to enable Swagger middleware JSON
doc,
and UI:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My Test1 Api v1");
});
Asynchronous JavaScript and Xml, is a technique used to create more dynamic and interactive web app. It allows web page to request data from a server and update part of web page without reloading entire page.
Commonly used:
How it works:
XMLHttpRequest (XHR) or new
fetch() API.
<button type="button" onclick="loadData()"> Load Data</button>
<div id="content"></div>
function loadData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("content").innerHTML = xhr.responseText;
}
};
xhr.send();
}
// MODERN approach using fetch()
function loadData() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
document.getElementById('content').innerHTML = JSON.stringify(data);
})
.catch(error => console.error('Error:', error));
}
Mention what is the difference between AJAX and REST?
| AJAX | Is a client-side technique, allows a web page to send and receive data async from a server without refreshing an entire page; it updates part of web page. |
Use JS to make async request to server by using
XMLHttpRequest() or
fetch() methods.
|
Can be either stateful or stateless. | Ex: when we search for something in Google, AJAX is used to fetch search results. |
|---|---|---|---|---|
| REST | Is an architectural style for web services and APIs. | Uses HTTP methods to interact with resources on server in a stateless manner. | Perform CRUD operations. | 3rd party API used by developers to access tweets, weather, etc. |
JSON web token, is an open standard used for securely transfer information between parties as a JSON obj, it is widely used for authorization and authentication, where server return token after successful user login, and use this token for subsequent request to access protected resource. Jwt is not encrypted by default, meaning data in Payload can be visible to anyone who has token. If sensitive data needs to transfer, encryption should be used in addition to signing. Has 3 concept:
Header has 2 part: The type of the token (which is "JWT" in this case). The signing algorithm used (e.g., HMAC SHA256 or RSA).
{
"alg": "HS256", // HMAC-SHA256
"typ": "JWT" // Token type is JWT
}
Payload: contains claims, typically user. It can be :
{
"sub": "2354", // User ID
"name": "Firuza", // Name of the user
"admin": true, // Admin flag
"iat": 1516239022 // Time when the JWT was issued
}
Signature: ensure token is not tampered, To create the signature, we combine the encoded header, encoded payload, and a secret key, using the algorithm specified in the header (e.g., HMACSHA256).
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload), secretKey
)
The Header and Payload automatically created and encoded in JwtSecurityTokenHandler library(which provides methods to read, validate, and write JWTs) based on based on the SecurityTokenDescriptor informations. Inside SecurityTokenDescriptor we define header and payload. The header is generated automatically based on the signing credentials (SigningCredentials) and the type of algorithm you choose (in this case, HmacSha256Signature). The payload is generated based on Subject(claims) credentials and expires. Ex;
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "John Doe"),
new Claim(ClaimTypes.Role, "Admin")
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var jwt = tokenHandler.WriteToken(token);
Access Token: is a short lived token that allow the client to access specific resource, typically contains user information (claims) and permission (role). passed along with API request within Authorization header ; Authorization: Bearer <access_token> , ensure that user is authenticated and authorized to perform action. when login, then token is generated, then sends to client. client include this token for subsequent request. it has short life time like 15min/few hours for security. are not stored on the server or database, as they are stateles, usually stored on client side:
// Store JWT in local storage
localStorage.setItem("token", "your-jwt-token");
// Retrieve JWT from local storage
fetch('/api/protected-resource', {
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('accessToken')
} });
is a long lived token that allow the client to obtain a new access token without re-authenticating the user(without login again). When user login the server respond with 2 token: Access and Refresh tokens. But after access token expires , normally we would not be able to make any request, then client application automatically send the refresh token to the server to get a new Access Token. Keep user as logged in and have no longer expiration time. Are stored on the server or database, because they need to be validated and managed securely. Is also stored on client side (secure cookies). Are more sensitive as they have longer lifespan (weeks, months).
is the process of checking if a given token (like AC) is valid. Include verifying its signature , checking if it has expired, and ensure the claims are legal. if token isn't valid the request rejected. When validating token, we use ClaimsPrincipal, It extract claims from token like ID, Role and server now can use these claims to authorize access to different resources. For validation we use TokenValidationParameters which specifes rules to validate token. It has:
ValidateIssuer = true;
ValidIssuer = "https://auth.yourapp.com";
ValidateAudience = true;
ValidAudience = "https://api.example.com";
IssuerSigningKey = new SymmetricSecurityKey(key); // Your secret key
ValidateIssuerSigningKey = true;
ClockSkew = TimeSpan.FromMinutes(5);
RequireExpirationTime = true;
‘Encoding : rocess of converting data from one type to another. Allow data to be represented in safe format, then decoded back later.
Decoding : convert encoded string back to its original form, like convert base64 to binary.
Base64 : is encoding scheme used to convert binary data into text format, so this encode data which can be transferred over HTTP, EMAIL, HTML. How works: Computer process and store data in binary (1,0) , but some protocols expect data as text. son base64 convert this binary data into string of characters. this characters can be A-Z, a-z, 0-1, + and / in JWT concept, we use Base64 to encode Header and Payload. In Email concept, we use to encode attachments. In HTML concept, we use to embed image or other files in HTML/CSS.
Base64URL : is used for encoding, which is similar to Base64 but with URL-safe characters.
How works :
Advantages :
Disadvantages :
JWT encryption : can be done using JWE (json web encryption) standard. Ensure that content of token is unreadable by both side. We install library called System. IdentityModel.Tokens.Jwt and generate RSA:
// Generate RSA keys
RSA rsa = RSA.Create();
var rsaPublicKey = rsa.ExportParameters(false);
var rsaPrivateKey = rsa.ExportParameters(true);
| Session Based | JWT |
|---|---|
| The server stores user session data . e.g: user send credentials to server, if credentials are correct the server create session for user and store information in DB. Server has full control over session. The session identified by its unique SessionID. Then sever send this sessionID to client and store in cookie. For each subsequest request, client send this ID to back server using cookie and allow server to verify user's identity. It has expiration time (after30min logs out). better for traditional server-rendered applications. | The server does not store any session data. The JWT containing all necessary information, and the client stores the cookie. Ideal for modern application like microservice. |
is a protocol that allow one application to access resource or perform action on a user without getting their password. Instead, it uses tokens to give permission for limited duration. Flow: application request permission to access resources, we give permission and application use token to access only what we allow. e.g: we want to sign up for app (fitness tracker) and allow app to access our google calendar to track our workout.