Proxy: Controlling Access to Objects Without Changing Their Interface
Design Patterns Explained: From Theory to Practice: Article 13
Imagine a ticket-management application where users can attach screenshots, documents and diagnostic logs to support tickets.
These files are stored in an external object-storage service. When a user requests an attachment, the application must retrieve the file and return it to the caller.
However, not every user should be allowed to access every attachment. A user might belong to one support team while the attachment belongs to a ticket managed by another team.
We could add access checks directly to every class that retrieves attachments. But this approach risks duplicating authorisation logic across the application. It also makes it easier for a new feature or service to accidentally bypass those checks.
What if we introduced an object that sits between the application and the actual attachment service, controlling access before forwarding requests?
That is the idea behind the Proxy pattern.
What is the Proxy pattern?
The Proxy pattern provides a substitute or placeholder for another object, allowing us to control access to that object without changing the interface clients use.
Rather than communicating directly with the original object, clients interact with the proxy. The proxy can perform additional operations before forwarding requests to the underlying service.
Depending on the problem being solved, this additional behaviour might include:
- Controlling access based on permissions.
- Delaying the creation of an expensive object until it is needed.
- Forwarding requests to a remote service.
- Caching results to avoid unnecessary operations.
- Managing access to a resource or object throughout its lifecycle.
The important characteristic is that the proxy and the real object share the same interface. From the client's perspective, both can be used in the same way.
In our ticket-management example, the proxy will check whether the current user is allowed to retrieve an attachment before forwarding the request to the actual storage implementation.
Understanding the participants
The Proxy pattern has four main participants:
Participant| Responsibility
Service Interface| Defines the operations that both the real service and proxy must implement.
Real Service| Performs the actual operation requested by the client.
Proxy| Implements the same interface, controls access to the real service and forwards permitted requests.
Client| Communicates with the service through the shared interface without needing to know whether it is using a proxy or the real implementation.
The relationship can be illustrated as follows:
Client
|
v
Service Interface
|
v
Authorised Proxy
|
v
Real Service
|
v
Object Storage
The client communicates with the proxy through the service interface. The proxy performs its checks and delegates the operation to the real service when appropriate.
Let's implement this in C#.
Implementing Proxy in C#
1. Defining the service interface
We begin with an interface that describes how the application retrieves ticket attachments.
public interface ITicketAttachmentReader
{
Task<Stream> OpenReadAsync(
Guid attachmentId,
CancellationToken cancellationToken = default);
}
The interface exposes one operation: retrieve a readable stream for an attachment.
Neither the client nor the interface needs to know where the file is stored or how it is retrieved.
This abstraction allows us to provide different implementations without changing the code that depends on it.
2. Implementing the real service
Next, we create the actual attachment reader.
It retrieves the attachment metadata from the repository and uses an object-storage client to open the file.
internal sealed class BlobTicketAttachmentReader
: ITicketAttachmentReader
{
private readonly ITicketAttachmentRepository _repository;
private readonly IBlobObjectClient _blobClient;
public BlobTicketAttachmentReader(
ITicketAttachmentRepository repository,
IBlobObjectClient blobClient)
{
_repository = repository;
_blobClient = blobClient;
}
public async Task<Stream> OpenReadAsync(
Guid attachmentId,
CancellationToken cancellationToken = default)
{
var attachment = await _repository.GetByIdAsync(
attachmentId,
cancellationToken);
if (attachment is null)
{
throw new TicketAttachmentNotFoundException(
attachmentId);
}
return await _blobClient.OpenReadAsync(
attachment.StorageKey,
cancellationToken);
}
}
"BlobTicketAttachmentReader" is our Real Service. It contains the implementation details required to retrieve an attachment.
The example assumes that "ITicketAttachmentRepository" retrieves attachment metadata and "IBlobObjectClient" communicates with the configured object-storage provider.
Notice that the real service does not contain the access-control logic. Its responsibility is to retrieve the requested attachment.
We will keep this implementation internal to the infrastructure layer so application code depends on the interface rather than directly resolving the real implementation.
3. Creating the protection proxy
Now we introduce the proxy.
Our "AuthorisedTicketAttachmentReaderProxy" implements "ITicketAttachmentReader", just like the real service.
However, before forwarding a request, it checks whether the current user has permission to read the requested attachment.
First, we define an access-policy abstraction:
public interface ITicketAttachmentAccessPolicy
{
Task<bool> CanReadAsync(
Guid attachmentId,
CancellationToken cancellationToken);
}
The policy implementation is responsible for checking the current authenticated user's permissions against the requested attachment.
Importantly, we do not pass a user ID supplied by the client. The policy should obtain the user's identity from trusted server-side authentication context.
Now we can implement the proxy:
public sealed class AuthorisedTicketAttachmentReaderProxy
: ITicketAttachmentReader
{
private readonly ITicketAttachmentReader _inner;
private readonly ITicketAttachmentAccessPolicy _accessPolicy;
public AuthorisedTicketAttachmentReaderProxy(
ITicketAttachmentReader inner,
ITicketAttachmentAccessPolicy accessPolicy)
{
_inner = inner;
_accessPolicy = accessPolicy;
}
public async Task<Stream> OpenReadAsync(
Guid attachmentId,
CancellationToken cancellationToken = default)
{
var canRead = await _accessPolicy.CanReadAsync(
attachmentId,
cancellationToken);
if (!canRead)
{
throw new UnauthorizedAccessException(
"You are not permitted to access this attachment.");
}
return await _inner.OpenReadAsync(
attachmentId,
cancellationToken);
}
}
There are two important things happening here.
First, the proxy implements exactly the same interface as the real service. It can therefore be substituted wherever an "ITicketAttachmentReader" is expected.
Second, it controls when the real service is accessed. If the user does not have permission, the proxy stops the operation. The underlying storage service is never called.
This is the central idea of a protection proxy: control access to an object without changing the way clients interact with it.
The application should translate access-denial exceptions into the appropriate HTTP response through its exception-handling strategy. Depending on the security requirements, it may also avoid revealing whether an inaccessible attachment exists.
4. Configuring the proxy with dependency injection
We now need to ensure that application services receive the proxy rather than the real attachment reader.
ASP.NET Core dependency injection makes this straightforward.
builder.Services.AddScoped<ITicketAttachmentAccessPolicy,
TicketAttachmentAccessPolicy>();
builder.Services.AddScoped<BlobTicketAttachmentReader>();
builder.Services.AddScoped<ITicketAttachmentReader>(
serviceProvider =>
new AuthorisedTicketAttachmentReaderProxy(
serviceProvider.GetRequiredService<
BlobTicketAttachmentReader>(),
serviceProvider.GetRequiredService<
ITicketAttachmentAccessPolicy>()));
The real implementation is registered so that the proxy can receive it as its inner service. However, application services should depend only on "ITicketAttachmentReader".
For example:
public sealed class TicketDownloadService
{
private readonly ITicketAttachmentReader _attachmentReader;
public TicketDownloadService(
ITicketAttachmentReader attachmentReader)
{
_attachmentReader = attachmentReader;
}
public Task<Stream> DownloadAsync(
Guid attachmentId,
CancellationToken cancellationToken)
{
return _attachmentReader.OpenReadAsync(
attachmentId,
cancellationToken);
}
}
"TicketDownloadService" does not know whether it is interacting with the proxy or the real implementation.
The dependency injection container supplies the proxy, which performs the access check before delegating to the real service.
Notice that "DownloadAsync()" returns the "Task<Stream>" directly without using "await". This is perfectly valid when a method simply forwards an asynchronous operation.
There is also an important resource-management detail: the caller that receives the stream is responsible for disposing it. A stream may hold an open connection to object storage, so it should be disposed when the download is complete. In an ASP.NET Core endpoint, this responsibility should be handled explicitly by the code that consumes or returns the stream.
We use scoped registrations because the proxy and access policy may depend on request-specific identity information and other scoped services. A scoped service should not be captured by a singleton.
This example also demonstrates why the real implementation should not be exposed as an alternative application dependency. Every access path must go through the intended boundary; otherwise, callers could bypass the proxy entirely.
5. Understanding other types of proxies
Our implementation demonstrates a protection proxy, but the pattern has several variations.
The underlying structure remains similar, but the reason for introducing the proxy changes.
Proxy type| Purpose| Example
Protection Proxy| Controls access based on permissions or rules.| Checking whether a user can download a ticket attachment.
Virtual Proxy| Delays the creation or loading of an expensive object.| Loading a large ticket report or document preview only when requested.
Remote Proxy| Represents an object located in another process or on another machine.| A client-side object forwarding calls to a remote ticket service.
Caching Proxy| Stores previously retrieved results to avoid repeating expensive operations.| Reusing ticket metadata retrieved from an external service.
These variations demonstrate that the Proxy pattern is not limited to security.
It provides a general mechanism for placing an intermediary between a client and an object, giving us control over how that object is accessed.
When should you use the Proxy pattern?
The Proxy pattern is useful when direct access to an object introduces concerns that should be handled separately from its primary responsibility.
Consider using it when:
- Access to a service must be controlled consistently across multiple clients.
- Creating or loading an object is expensive and should be delayed.
- Communication with a remote service needs to be represented through a local interface.
- Repeated requests can benefit from caching.
- You need to manage access to an object without changing its implementation.
However, a proxy should not automatically be introduced whenever an application needs authorisation.
For example, ASP.NET Core already provides endpoint authorisation and resource-based authorisation through "IAuthorizationService". These may be sufficient for many applications.
A protection proxy becomes more interesting when access control needs to be enforced at a service boundary that is shared by several application components.
It is also important to remember that a proxy does not automatically make an underlying resource secure. The real service and its storage infrastructure must still be protected against direct, unauthorised access.
Advantages and trade-offs
Advantages
- Separation of concerns: Access control, caching or remote communication can be handled without adding those responsibilities to the real service.
- Consistent access: Clients interact through a common interface, allowing the proxy to apply its rules before delegating operations.
- Reduced client complexity: Clients do not need to understand the internal details of how an object is accessed or managed.
- Flexibility: The proxy can be introduced without changing the interface expected by existing clients.
Trade-offs
- Additional complexity: The proxy introduces another class and another layer of indirection.
- Performance overhead: Every request passes through the proxy, and additional checks or network calls can increase latency.
- Hidden behaviour: Clients may not immediately realise that an operation involves authorisation checks, caching or remote communication.
- More difficult debugging: Understanding the complete execution path requires following both the proxy and the real service.
- Consistency concerns: Caching proxies must handle invalidation and stale data, while protection proxies must ensure access checks cannot be bypassed.
The pattern is useful when the additional control provides meaningful value. For simple services that do not require an intermediary, calling the real implementation directly is often sufficient.
Proxy vs Adapter vs Decorator vs Facade
The Proxy pattern shares structural similarities with several other patterns we have already explored. Understanding their different intentions makes it easier to choose the right one.
Pattern| Primary intention| Key distinction
Adapter| Make incompatible interfaces work together.| Changes the interface clients interact with.
Decorator| Extend an object's behaviour without modifying its class.| Adds responsibilities to an object, often dynamically.
Facade| Simplify interactions with a complex subsystem.| Provides a simplified interface to multiple underlying components.
Proxy| Control access to another object.| Provides a substitute that clients can use through the same interface.
Proxy and Decorator are particularly easy to confuse because both can implement the same interface as the object they wrap and delegate operations to an underlying instance.
The difference is primarily their intent.
A Decorator focuses on adding responsibilities or behaviour. A Proxy focuses on controlling access to the underlying object, its creation, location or usage.
For example, our "AuthorisedTicketAttachmentReaderProxy" controls whether a request reaches the real service. A decorator around the same service might instead record download activity or measure execution time.
The distinction is not always visible in the class structure. It comes from the problem the design is intended to solve.
Conclusion
The Proxy pattern provides a way to control access to an object without changing the interface clients use.
In our ticket-management application, the protection proxy separates attachment retrieval from access-control concerns. The real service remains focused on retrieving files, while the proxy ensures that requests are checked before reaching it.
More broadly, the pattern can support lazy initialisation, remote communication and caching.
Like the other structural patterns, Proxy is not something we should introduce simply because it is available. The additional layer should solve a genuine design problem.
With Proxy, we have reached the end of the structural patterns section of this series. We have explored how Adapter, Bridge, Composite, Decorator, Facade, Flyweight and Proxy help us organise relationships between objects and responsibilities.
Next, we move into behavioural design patterns, beginning with Chain of Responsibility — a pattern for passing requests through a sequence of potential handlers without tightly coupling the sender to a specific receiver.
Further reading
1. Alexander Shvets — Dive Into Design Patterns, Proxy chapter.
2. Vaskaran Sarcar — Design Patterns in C#, 2nd Edition, Proxy Pattern.
3. Microsoft Learn — "Resource-based authorisation in ASP.NET Core MVC" (https://learn.microsoft.com/en-us/aspnet/core/mvc/security/authorization/resource-based?view=aspnetcore-10.0).
4. Microsoft Learn — "Policy-based authorisation in ASP.NET Core" (https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies).
5. Microsoft Learn — "Dependency injection service lifetimes" (https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection/service-lifetimes).
Comments
Join the discussionNo comments yet. Be the first to comment.