8 Securing In Asp Net Core Application

NET Centric Computing · Unit 8 · 5 hrs

Securing in ASP.NET Core Application

Exam-focused notes for Securing in ASP.NET Core Application (NET Centric Computing, CSC378): what the TU syllabus asks and how it has actually been tested, with 8 solved past questions from this unit.

Securing in ASP.NET Core Application in short

This unit covers securing an ASP.NET Core application: authenticating who a request is from with ASP.NET Core Identity, wiring authentication into an application, authorizing what an authenticated user can do with roles, claims, and policies, protecting individual controllers and actions, and recognizing the common web vulnerabilities every ASP.NET Core developer needs to defend against.

Securing in ASP.NET Core Application: notes

Authentication: ASP.NET Core Identity

Authentication is the process of determining who made a request; once a request is authenticated, the application can decide whether that identity is allowed to perform the requested action, which is authorization. ASP.NET Core Identity is an API that supplies user-interface login functionality and manages users, passwords, profile data, roles, claims, tokens, and email confirmation, among other concerns. A user can register a local account whose credentials Identity stores itself, or sign in through an external login provider such as Google, Facebook, Microsoft, or Twitter. Identity is commonly configured to store user names, passwords, and profile data in a SQL Server database through Entity Framework Core, but any persistent store, such as Azure Table Storage, can be used instead.

Adding authentication to apps and identity service configurations

Wiring Identity into an ASP.NET Core application follows a consistent sequence. First, the Entity Framework Core and Identity NuGet packages are installed (the EF Core provider for SQL Server, the EF Core tools, and the Identity packages). Second, an application DbContext is created that inherits from IdentityDbContext instead of the plain DbContext, so that Identity's own tables (users, roles, claims, and so on) are included in the model:

public class AppDbContext : IdentityDbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

Third, the context and the Identity services are registered in ConfigureServices:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer("Server=.;Database=AppDb;Trusted_Connection=True;"));

    services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<AppDbContext>();
}

Fourth, the authentication middleware is added to the request pipeline in Configure, which must run before authorization so that a request's identity is known before access decisions are made:

public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();
    app.UseAuthorization();
}

Finally, an EF Core migration is created and applied so that Identity's tables actually exist in the database, using the package manager console commands Add-Migration AddingIdentity followed by Update-Database.

What this unit covers

  • Authentication: ASP.NET Core Identity
  • Adding authentication to apps and identity service configurations
  • Authorization: Roles, Claims and Policies
  • Securing Controllers and Action Methods
  • Common Vulnerabilities: Cross-site Scripting attacks, SQL Injection attacks, Cross-site Request Forgery (CSRF), Open Redirect Attacks

Authorization

2081 · 5 marks

Distinguish between roles and policies. Explain about Kestrel web server in ASP.NET core. [5]

Show solved answer

Roles vs Policies and Kestrel Web Server in ASP.NET Core


Part 1: Distinguish Between Roles and Policies

BasisRolesPolicies
DefinitionRoles are a way to group users based on their job or function (e.g., Admin, User, Manager)Policies are a set of requirements that must be satisfied for authorization to succeed
ApproachRole-based authorization checks if a user belongs to a specific rolePolicy-based authorization checks one or more requirements against the current user
FlexibilityLess flexible; limited to simple role membership checksMore flexible; can combine multiple requirements (claims, roles, custom logic)
DeclarationDeclared using [Authorize(Roles = "Admin")]Declared using [Authorize(Policy = "PolicyName")]
ConfigurationRoles are assigned directly to usersPolicies are defined in Startup.cs using AddAuthorization()
ComplexitySuitable for simple access control scenariosSuitable for complex, fine-grained access control scenarios
ExampleA user is in the "Admin" roleA policy may require a user to be over 18 AND have a verified email

Part 2: Kestrel Web Server in ASP.NET Core

Definition

Kestrel is a cross-platform, lightweight web server for ASP.NET Core. It is the web server that is included by default in ASP.NET Core project templates and is built into the ASP.NET Core framework.


Key Features of Kestrel

  • Cross-platform: Kestrel runs on Windows, Linux, and macOS, making ASP.NET Core applications truly cross-platform.
  • Default web server: It is automatically included when an ASP.NET Core project is created using the default templates.
  • High performance: Kestrel is designed to be fast and efficient for handling HTTP requests.
  • Self-hosted: It can run independently without requiring an external web server.

Hosting Models Using Kestrel

There are two ways Kestrel is used in the Out-of-Process Hosting Model:

1. Using Kestrel Directly (Edge Server)

  • Kestrel itself acts as an edge server, which directly serves user requests from the internet.
  • No additional web server (like IIS or NGINX) is needed.
  • Suitable for simpler applications or internal services.
Browser Request --> Kestrel Server --> ASP.NET Core Application

2. Using Kestrel with a Reverse Proxy Server

  • Due to limitations of Kestrel, it cannot be used in all scenarios (e.g., sharing a port, advanced security features).
  • In such cases, powerful servers like IIS, NGINX, or Apache act as a reverse proxy server.
  • The reverse proxy receives the request from the browser and redirects/forwards it to the internal Kestrel server.
  • Kestrel then processes the request and returns the response.
Browser Request --> Reverse Proxy (IIS/NGINX/Apache) --> Kestrel Server --> ASP.NET Core App

In-Process Hosting (IIS)

  • In this model, the ASP.NET Core app is hosted inside the IIS worker process (w3wp.exe).
  • IIS forwards web requests to the backend ASP.NET Core app running the Kestrel server (out-of-process hosting model).

Summary

Kestrel is the heart of ASP.NET Core's web serving capability. It provides a fast, cross-platform, and lightweight server that can either work standalone as an edge server or work behind a powerful reverse proxy like IIS or NGINX for production-grade deployments.

Open this answer on its own page →

2080 · 5 marks

Define claim and policy in terms of authorization. How and when do you create hidden fields? [5]

--- A claim is a name-value pair that represents a piece of information about a user. It describes who the user is, not what they can do. Claims are issued by a trusted authority and are stored in the user's identity. Examples of claims: - Name: "John", Role: "Admin" - Email: "[email protected]" -...

Open this answer on its own page →

2079 · 5 marks

How do you assign roles, claims and policies? Explain with an example. [5]

Authorization in ASP.NET Core is handled through three main mechanisms: Roles, Claims, and Policies. --- A role is a label assigned to a user that defines what group they belong to (e.g., Admin, User, Manager). Role-based authorization checks whether a user belongs to a specific role before grant...

Open this answer on its own page →

Common Vulnerabilities

2080 · 5 marks

Explain the chances of SQL injection attack with a scenario. [5]

SQL Injection (SQLI) is a common attack vector that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. It usually occurs when a user provides an SQL statement as input instead of the expected value (such as a username or password...

Open this answer on its own page →

2079 · 10 marks

Explain the uses of cookies. What types of vulnerabilities can occur in web application? Show the case of Cross-site Scripting attack.[10]

--- A cookie is a small piece of data stored on the client's browser by the web server. Cookies are used to maintain state information between the client and server across multiple HTTP requests (since HTTP is stateless). Use Description ------------------ Session Management Storing session IDs s...

Open this answer on its own page →

2079 · 5 marks

What types of problems lead to SQL injection attack? Discuss any two types of ASP.Net host models. [5]

--- SQL Injection (SQLi) is a common attack vector that uses malicious SQL code for backend database manipulation to access information that was not intended to be displayed. This information may include sensitive data, user lists, or private customer details. 1. No Input Validation When user inp...

Open this answer on its own page →

2078 · 5 marks

Define open redirect attacks. Discuss about docker and containerization. [5]

Show solved answer

Open Redirect Attacks and Docker/Containerization


Part 1: Open Redirect Attacks (2 marks)

An open redirect attack is a web security vulnerability where an attacker manipulates a web application to redirect users to an arbitrary, potentially malicious external URL without proper validation.

How It Works:

  • Web applications often use URL parameters to redirect users after an action (e.g., login).
  • Example of a vulnerable URL:
    https://trustedsite.com/login?returnUrl=https://malicious.com
    
  • If the application does not validate the returnUrl parameter, the user is silently redirected to the attacker's site.

Common Consequences:

  • Phishing attacks: Users are redirected to fake login pages to steal credentials.
  • Malware distribution: Users are sent to sites hosting malicious downloads.
  • Credential harvesting: Combined with XSS (Cross-Site Scripting), attackers can steal cookies and session tokens (as noted in the reference: XSS can "redirect the browser to another page").

Prevention:

  • Validate and whitelist all redirect URLs.
  • Avoid using user-supplied input directly in redirect logic.
  • Use relative URLs instead of absolute URLs for redirects.

Part 2: Docker and Containerization (3 marks)

Containerization

Containerization is a lightweight form of virtualization where an application and all its dependencies (libraries, configuration files, runtime) are packaged together into a single unit called a container. Containers run in isolated environments on the host operating system without needing a full virtual machine.

Key Characteristics:

  • Containers share the host OS kernel (unlike VMs which have separate OS).
  • Lightweight, fast to start, and portable.
  • Ensures "works on my machine" consistency across environments (development, testing, production).

Docker

Docker is the most widely used platform for building, shipping, and running containers. It provides tools and a runtime to create and manage containers easily.

Core Docker Concepts:

ConceptDescription
Docker ImageA read-only template/blueprint used to create containers (e.g., an image with Node.js + app code)
Docker ContainerA running instance of a Docker image
DockerfileA script containing instructions to build a Docker image
Docker HubA public registry to store and share Docker images
Docker EngineThe runtime that builds and runs containers

Basic Dockerfile Example:

FROM node:14
WORKDIR /app
COPY . .
RUN npm install
CMD ["node", "server.js"]

Advantages of Docker and Containerization:

  1. Portability: Containers run consistently across any environment (local, cloud, server).
  2. Isolation: Each container runs independently, preventing conflicts between applications.
  3. Efficiency: Containers are lightweight compared to virtual machines as they share the host OS kernel.
  4. Scalability: Containers can be easily scaled up or down using orchestration tools like Kubernetes.
  5. Faster Deployment: Applications can be deployed quickly using pre-built images.
  6. Version Control: Docker images can be versioned, allowing easy rollback.

Docker vs Virtual Machine:

FeatureDocker ContainerVirtual Machine
OSShares host OS kernelHas its own OS
SizeMegabytesGigabytes
Startup TimeSecondsMinutes
PerformanceNear nativeOverhead due to hypervisor

Note: The reference notes provided do not directly cover open redirect attacks or Docker. The above answer is based on standard, correct Computer Science knowledge appropriate for BSc CSIT curriculum, with open redirect attacks linked to the XSS/redirect concepts mentioned in the reference context (ctx3).

Open this answer on its own page →

2078 · 5 marks

How can you prevent SQL injection attack? Explain with an example. [5]

SQL Injection is a security vulnerability where an attacker inserts or "injects" malicious SQL code into an input field, which is then executed by the database. This can allow attackers to bypass authentication, access unauthorized data, or even destroy the database. --- Consider the following ac...

Open this answer on its own page →