Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
.NET
.NET Core
.NET MAUI
.NET Standard
Active Directory
ADO.NET
Agile Development
AI
AJAX
AlbertAGPT
Alchemy
Alexa Skills
Algorand
Algorithms in C#
Android
Angular
ArcObject
ASP.NET
ASP.NET Core
Augmented Reality
Avalanche
AWS
Azure
Backbonejs
Big Data
BizTalk Server
Blazor
Blockchain
Bootstrap
Bot Framework
Business
Business Intelligence(BI)
C#
C# Corner
C# Strings
C, C++, MFC
Career Advice
Careers and Jobs
Chapters
ChatGPT
Cloud
Coding Best Practices
Cognitive Services
COM Interop
Compact Framework
Copilot
Cortana Development
Cosmos DB
Cryptocurrency
Cryptography
Crystal Reports
CSS
Current Affairs
Custom Controls
Cyber Security
Data Mining
Data Science
Databases & DBA
Databricks
Design Patterns & Practices
DevExpress
DevOps
DirectX
Dynamics CRM
Enterprise Development
Entity Framework
Error Zone
Exception Handling
F#
Files, Directory, IO
Flutter
Games Programming
GDI+
General
Generative AI
GO
Google Cloud
Google Development
Graphics Design
Graphite Studio
Hardware
Hiring and Recruitment
HoloLens
How do I
HTML 5
Infragistics
Internet & Web
Internet of Things
Ionic
Java
Java and .NET
JavaScript
JQuery
JSON
JSP
Knockout
Kotlin
Langchain
Leadership
Learn .NET
Learn iOS Programming
LINQ
Machine Learning
Metaverse
Microsoft 365
Microsoft Fabric
Microsoft Office
Microsoft Phone
Microsoft Teams
Mobile Development
MongoDB
MuleSoft
MySQL
NEAR
NetBeans
Networking
NFT
NoCode LowCode
Node.js
Office Development
OOP/OOD
Open Source
Operating Systems
Oracle
Outsourcing
Philosophy
PHP
Polygon
PostgreSQL
Power Apps
Power Automate
Power BI
Power Pages
Printing in C#
Products
Progress
Progressive Web Apps
Project Management
Public Speaking
Python
Q#
QlikView
Quantum Computing
R
React
React Native
Reports using C#
Robotics & Hardware
RPA
Ruby on Rails
RUST
Salesforce
Security
Servers
ServiceNow
SharePoint
Sharp Economy
SignalR
Smart Devices
Snowflake
Software Architecture/Engineering
Software Testing
Solana
Solidity
Sports
SQL
SQL Server
Startups
Stratis Blockchain
Swift
SyncFusion
Threading
Tools
TypeScript
Unity
UWP
Visual Basic .NET
Visual Studio
Vue.js
WCF
Wearables
Web API
Web Design
Web Development
Web3
Windows
Windows Controls
Windows Forms
Windows PowerShell
Windows Services
Workflow Foundation
WPF
Xamarin
XAML
XML
XNA
XSharp
Register
Login
0
Answer
DelegateHandler to RequestDelegate migrate asp.net core 3.1
Rupesh K
4y
1.7k
1
Reply
I am trying to migrate the DelegateHandler apikey authentication to RequestDelegate apikey authentication.I was able to create below code ,but need clarification wheather the code configuration is correct and how to return error code if any condition fails in "async Task Invoke" method of DelegatingHandler class.
Using RequestDelegate:
public
class
DelegatingHandler {
private
readonly
RequestDelegate _next;
private
readonly
ILogger _logger;
private
ISecurityService _securityService;
public
DelegatingHandler(RequestDelegate next, ILogger logger, ISecurityService securityService) {
_next = next;
_logger = logger;
_securityService = securityService;
}
public
async Task Invoke(HttpContext context, HttpRequestMessage request) {
try
{
//Get API Key
string
apiKey = request.ApiKey();
//Check for APIKEY in header and if null retun error code with message
if
(apiKey ==
null
|| apiKey.Trim().Equals(
string
.Empty)) {
//Not sure this is correct,Please correct what to be added to return error status
new
HttpResponseMessage(HttpStatusCode.Unauthorized) {
Content =
new
StringContent(
"Header information for ApiKey is missin"
)
};
}
string
message =
""
;
//Splitting the UserName and Key, the format will he username:key
string
[] identity = apiKey.Split(
':'
);
if
(!IsAuthorized(identity, request.RequestUri.AbsolutePath.ToString(), request.Method.ToString(),
ref
message)) {
//Not sure this is correct,Please correct what code to be added to return error status
new
HttpResponseMessage(HttpStatusCode.Unauthorized) {
Content =
new
StringContent(
"Header information for ApiKey is missin"
)
};
}
else
{
//Setting the identity
IPrincipal principal =
new
GenericPrincipal(
new
GenericIdentity(identity[0]),
null
);
Thread.CurrentPrincipal = principal;
_logger.Info(message,
new
{
EndPoint = request.RequestUri.AbsolutePath.ToString(),
UserName = Thread.CurrentPrincipal.Identity.Name
});
}
await _next.Invoke(context);
}
catch
(Exception ex) {
//Not sure this is correct,Please correct what code to be added to return error status
new
HttpResponseMessage(HttpStatusCode.InternalServerError) {
Content =
new
StringContent(ex.ToString())
};
}
}
private
bool
IsAuthorized(
string
[] identity,
string
requestAbsolutePath,
string
httpMethod,
ref
string
message) {
try
{
//Make a DB call and check from _securityService call ,DO we need to register them in Startup class
message =
"Unauthorized to access the requested resource"
;
}
catch
(Exception ex) {
message = ex.Message;
_logger.Error(
"VSphereDelegationHandler Failed"
,
new
{
Method =
"IsAuthorized"
}, ex);
}
return
false
;
}
}
APIKey Extension:
public
static
class
ApiKeyExtensions {
public
static
IApplicationBuilder UseApiKey(
this
IApplicationBuilder builder) {
return
builder.UseMiddleware < VSphereDelegatingHandler > ();
}
}
In the startup.cs class do we need to register all the service Interface and Class files ,but I am getting error in program.cs
Program.cs
public
class
Program {
public
static
void
Main(
string
[] args) {
CreateHostBuilder(args).Build().Run();
}
public
static
IHostBuilder CreateHostBuilder(
string
[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseStartup < Startup > ();
});
}
StartUp.cs
public
class
Startup
{
public
Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public
IConfiguration Configuration {
get
; }
// This method gets called by the runtime. Use this method to add services to the container.
public
void
ConfigureServices(IServiceCollection services,
string
dbConnectionString)
{
services.AddControllers();
services.AddScoped<ISecurityService, SecurityService>();
services.AddScoped<ISecurityDataService, SecurityDataService>();
services.AddScoped<ISecurityCheckService, SecurityCheckService>();
//Additional service are registered and is the below DB register is correct
services.AddScoped<IDBOps, DBOps>(db =>
new
DBOps(dbConnectionString));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public
void
Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if
(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseApiKey();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Post
Reset
Cancel
Answers (
0
)
Next Recommended Forum
action method (link) not working after publish my project
Deploying Asp.net Web application