You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Securing DMS, using ASP.Net Core Web Api Authentication
The documentation will be updated with a new sample on how to configure DMS with Web Api Authentication.
This sample is really simple, and is not secure by default, since you'll that the JWT Token is generated on the fly, and the key is hardcoded.
This sample explains how to configure ASP.Net Core Web APi regardless the identity provider you are using.
If you want to rely on a strong OAUTH2 / OpenID Connect provider, please read:
DMS relies on the ASP.NET Core Web Api architecture. So far, you can secure DMS like you're securing any kind of exposed Web API:
Configuring the controller
Configuring the identity provider protocol
Calling the controller with an authenticated client, using a bearer token
Add Authentication to your Web API
You need to configure your Web API project to be able to secure any controller.
In your Startup.cs, you should add authentication services,with JWT Bearer protection.
It involves using services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>{})
Here is a quick sample, without relying on any external cloud identity provider (once again, DON'T do this in production, it's INSECURE and just here for the sake of explanation)
publicvoidConfigureServices(IServiceCollectionservices){
services.AddControllers();// [Required]: Handling multiple sessions
services.AddMemoryCache();// Adding a default authentication system
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();// => remove default claims
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>{ValidIssuer="Dotmim.Sync.Bearer",ValidAudience="Dotmim.Sync.Bearer",IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes("RANDOM_KEY"))});// [Required]: Get a connection string to your server data sourcevarconnectionString= Configuration.GetSection("ConnectionStrings")["SqlConnection"];// [Required] Tables involved in the sync process:vartables=newstring[]{"ProductCategory","ProductModel","Product","Address","Customer","CustomerAddress","SalesOrderHeader","SalesOrderDetail"};// [Required]: Add a SqlSyncProvider acting as the server hub.
services.AddSyncServer<SqlSyncProvider>(connectionString, tables);}
As an example, if you're using Azure AD authentication, your code should be more like:
publicvoidConfigureServices(IServiceCollectionservices){
services.AddControllers();// [Required]: Handling multiple sessions
services.AddMemoryCache();// Using Azure AD Authentication
services.AddMicrosoftIdentityWebApiAuthentication(Configuration).EnableTokenAcquisitionToCallDownstreamApi().AddInMemoryTokenCaches();// [Required]: Get a connection string to your server data sourcevarconnectionString= Configuration.GetSection("ConnectionStrings")["SqlConnection"];// [Required] Tables involved in the sync process:vartables=newstring[]{"ProductCategory","ProductModel","Product","Address","Customer","CustomerAddress","SalesOrderHeader","SalesOrderDetail"};// [Required]: Add a SqlSyncProvider acting as the server hub.
services.AddSyncServer<SqlSyncProvider>(connectionString, tables);}
Finally, do not forget to add Authentication middleware:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.publicvoidConfigure(IApplicationBuilderapp,IWebHostEnvironmentenv){if(env.IsDevelopment()){
app.UseDeveloperExceptionPage();}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>{ endpoints.MapControllers();});}
Securing the controller
This part is the most easier one. Yo can choose to secure all the controller, using the [Authorize] attribute on the class itself, or you can use either [Authorize] or [AllowAnonymous] on each controller methods:
The simplest controller could be written like this, using :
And eventually, you can even have more control, using the HttpContext instance, from wiyhin your POST handler:
[HttpPost]publicasync Task Post(){// If you are using the [Authorize] attribute you don't need to check// the User.Identity.IsAuthenticated valueif(!HttpContext.User.Identity.IsAuthenticated){this.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;return;}// using scope and even claims, you can have more grain control on your authenticated userstringscope=(User.FindFirst("http://schemas.microsoft.com/identity/claims/scope"))?.Value;stringuser=(User.FindFirst(ClaimTypes.NameIdentifier))?.Value;if(scope!="access_as_user"){this.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;return;}await webServerManager.HandleRequestAsync(this.HttpContext);}
Calling the secure Web Api from you client
From you mobile / console / desktop application, you just need to send your bearer token embedded into your HttpClient headers.
The WebClientOrchestrator object allows you to use your own HttpClient instance. So far, create an instance and add your bearer token to the DefaultRequestHeaders.Authorization property
// Getting a JWT token// This sample is NOT SECURE at all// You should get a Jwt Token from an identity provider like Azure, Google, AWS or other.vartoken= GenerateJwtToken("spertus@microsoft.com","SPERTUS01");HttpClienthttpClient=new HttpClient();
httpClient.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("Bearer", token);// Adding the HttpClient instance to the web client orchestratorvarserverOrchestrator=new WebClientOrchestrator("https://localhost:44342/api/sync", client:httpClient);varclientProvider=new SqlSyncProvider(clientConnectionString);varagent=new SyncAgent(clientProvider, serverOrchestrator);varresult=await agent.SynchronizeAsync();
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
Securing DMS, using ASP.Net Core Web Api Authentication
The documentation will be updated with a new sample on how to configure
DMS
with Web Api Authentication.This sample is really simple, and is not secure by default, since you'll that the JWT Token is generated on the fly, and the key is hardcoded.
This sample explains how to configure ASP.Net Core Web APi regardless the identity provider you are using.
If you want to rely on a strong OAUTH2 / OpenID Connect provider, please read:
DMS
relies on the ASP.NET Core Web Api architecture. So far, you can secureDMS
like you're securing any kind of exposed Web API:Add Authentication to your Web API
You need to configure your Web API project to be able to secure any controller.
In your
Startup.cs
, you should add authentication services,with JWT Bearer protection.It involves using
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>{})
Here is a quick sample, without relying on any external cloud identity provider (once again, DON'T do this in production, it's INSECURE and just here for the sake of explanation)
As an example, if you're using Azure AD authentication, your code should be more like:
Finally, do not forget to add Authentication middleware:
Securing the controller
This part is the most easier one. Yo can choose to secure all the controller, using the
[Authorize]
attribute on the class itself, or you can use either[Authorize]
or[AllowAnonymous]
on each controller methods:The simplest controller could be written like this, using :
Maybe you'll need to expose the
GET
method to see the server configuration. In that particular case, we can use both[Authorize]
or[AllowAnonymous]
:And eventually, you can even have more control, using the
HttpContext
instance, from wiyhin yourPOST
handler:Calling the secure Web Api from you client
From you mobile / console / desktop application, you just need to send your bearer token embedded into your
HttpClient
headers.The
WebClientOrchestrator
object allows you to use your ownHttpClient
instance. So far, create an instance and add your bearer token to theDefaultRequestHeaders.Authorization
propertyIf you are using Azure AD to protect you Web Api, you can rely on this documentation, using MSAL.NET to call your secure endpoint: https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-mobile-app-configuration
Beta Was this translation helpful? Give feedback.
All reactions