Showing posts with label asp.net-core. Show all posts
Showing posts with label asp.net-core. Show all posts

Friday, September 21, 2018

VSCode: message: The preLaunch task 'build' terminated with exit code 1

Leave a Comment

OK. I am in .NetCore and using VSCode on Mac machine. Now, whenever I run my C# project then VSCode shows this annoying message:

The preLaunch task 'build' terminated with exit code 1

It shows me option to click on a button called show problems. When I click on this button, it only shows the warning messages. Now, if it was errors then its OK to see this message. But the fact that it shows this message every time there are warning(Which to me is OK). That is very annoying. Is there any way I can configure VS Code to not show these messages on things like warning?

2 Answers

Answers 1

It might be a problem with your task.json file, check the arguments of the file and make sure the build is pointing at the right location:

{     "version": "2.0.0",     "tasks": [         {             "label": "build",             "command": "dotnet",             "type": "process",             "args": [                 "build",                 "${workspaceFolder}/MyProject.csproj"             ],             "problemMatcher": "$msCompile"         }     ] } 

Answers 2

It means you're code isn't running properly as it has returned code 1.

Whenever vscode shows you this message, simply choose cancle and then go to your terminal. It should show you the problems. Then you should start debugging your code.

Please note that as you know, when debugging, Breakpoints lend the most help.

Read More

Thursday, September 20, 2018

ASP.NET Core- wrong processPath in generated web.config

Leave a Comment

I have rather strange problem.

One of the applications we are working on stopped working after publish to Azure Web App. Everything works ok locally. After long investigation, the culprit is that the web.config generated by the build (in VSTFS) has this:

<aspNetCore processPath=".\SomeServiceName.Api " stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

While the correct one is: <aspNetCore processPath=".\SomeServiceName.Api.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

Note the missing .exe.

The build output of the project is set to Console Application. It's ASP.NET Core app, running on full framwork. The build is run using Visual Studio Build task in VSTS, with following MSBuildArguments:

/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactstagingdirectory)"

If I run the build on my dev machine, using MSBuild cli, with the same command line arguments, I get this:

<aspNetCore processPath="dotnet" arguments=".\SomeServiceName.Api.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

The project is using <Project Sdk="Microsoft.NET.Sdk.Web">.

I'm guessing I could just add web.config to the project (it's not there at all now) and have it in source control the way I want, that should fix my immidiate problem of broken deployments. But I would like to know:

  1. The web.config genrated by build on VSTS is obviously wrong. Is that a bug in Microsoft.NET.SDK.Web thing?
  2. I don't have access to the actuall build server. I'm guessing that the only reasonable explanation is that someone updated .net core SDK, which is why the behaviour changed. Does this make sense? Does the msbuild targets come from .NET Core SDK, or is that part of visual studio?
  3. I'm getting different web.config on my machine. Why is that?

2 Answers

Answers 1

I had exactly the same problem, and I solved it last week. We had 2 ASP.Net Core projects, one showing the issue, the other didn't have the issue. So we compared the 2 .csproj files.

Turns out that in our case, all we needed to do was delete the

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">   <PlatformTarget>AnyCPU</PlatformTarget> </PropertyGroup> 

properties from the .csproj; once that was done, MSBuild correctly created the web.config, including the .exe at the end of the processPath.

Answers 2

A few options for getting the .exe in there. Each of these methods worked for me:

  1. Switch the build configuration from Debug (the default) to Release:

    dotnet publish -c Release or msbuild argument /p:Configuration=Release

  2. Create a web.config the way you want it in the root of your project and then tell the SDK not to touch it by adding the following to your project file:

    <PropertyGroup> <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled> </PropertyGroup>

  3. Specify your target runtime as one of the win-* runtimes listed at https://docs.microsoft.com/en-us/dotnet/core/rid-catalog. Here's the code that appears to be adding the exe extension:

    https://github.com/aspnet/websdk/blob/6b898ad0a39329ab5f0db281a9c1712e4303ed61/src/Publish/Microsoft.NET.Sdk.Publish.Targets/netstandard1.0/TransformTargets/Microsoft.NET.Sdk.Publish.TransformFiles.targets#L44

Read More

Thursday, September 13, 2018

How to prevent multiple login in SAAS application?

Leave a Comment

What I need to do

I'm developing an application using ASP.NET CORE and I actually encountered a problem using the Identity implementation.

In the official doc infact there is no reference about the multiple session, and this is bad because I developed a SaaS application; in particular a user subscribe a paid plan to access to a specific set of features and him can give his credentials to other users so they can access for free, this is a really bad scenario and I'll lose a lot of money and time.

What I though

After searching a lot on the web I found many solutions for the older version of ASP.NET CORE, so I'm not able to test, but I understood that the usually the solution for this problem is related to store the user time stamp (which is a GUID generated on the login) inside the database, so each time the user access to a restricted page and there are more session (with different user timestamp) the old session will closed.

I don't like this solution because an user can easily copy the cookie of the browser and share it will other users.

I though to store the information of the logged in user session inside the database, but this will require a lot of connection too.. So my inexperience with ASP.NET CORE and the lack of resource on the web have sent me in confusion.

Someone could share a generic idea to implement a secure solution for prevent multiple user login?

4 Answers

Answers 1

After searching a lot on the web I found many solutions for the older version of ASP.NET CORE, so I'm not able to test, but I understood that the usually the solution for this problem is related to store the user time stamp (which is a GUID generated on the login) inside the database, so each time the user access to a restricted page and there are more session (with different user timestamp) the old session will closed.

This is exactly what I do. My Users table has a SessionId and on every login the SessionId gets overwritten with a new Id. This session Id is checked on every request via a default policy in your authorization settings.

Create classes to validate the session.

public class ValidSessionRequirement : IAuthorizationRequirement {  }  public class ValidSessionHandler : AuthorizationHandler<ValidSessionRequirement> {     private readonly ApplicationDbContext _context;     private readonly ClaimsPrincipal _user;      public ValidSessionHandler(ApplicationDbContext context, ClaimsPrincipal user)     {         _context = context;         _user = user;     }      protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ValidSessionRequirement requirement)     {         if (!context.User.Identity.IsAuthenticated)             return;          // get user from database         var user = _context.Users.FirstOrDefault(e => e.Username == _user.Identity.Name);          // get session Id from user claims         var sessionId = _user.FindFirstValue("sessionId");          // if user isn't null and the session ID is the same then suceed the requirement         if (user != null && user.SessionId == sessionId)         {             context.Succeed(requirement);         }         return;     } } 

Configure your validation requirement in authorization settings

var defaultPolicy = new AuthorizationPolicyBuilder()     .RequireAuthenticatedUser()     .AddRequirements(new ValidSessionRequirement())     .Build();  services.AddAuthorization(options => {     options.DefaultPolicy = defaultPolicy; });  services.AddHttpContextAccessor();  builder.Services.AddTransient(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);  services.AddTransient<IAuthorizationHandler, ValidSessionHandler>(); 

So when you login, your other session is terminated. I prefer to do it this way so people don't have to worry about logging out of other devices. They can just overwrite the session each time. If two people are both using the same credentials, they will keep kicking each other out of the system.

Though, I'm using JWT token authentication and not cookie, so your implementation may be a little different.

Answers 2

You can use UpdateSecurityStamp to invalidate any existing authentication cookies. For example:

public async Task<IActionResult> Login(LoginViewModel model) {     var user = await _userManager.FindByEmailAsync(model.Email);     if (user == null)     {         ModelState.AddModelError(string.Empty, "Invalid username/password.");         return View();     }      if (await _userManager.ValidatePasswordAsync(user, model.Password))     {         await _userManager.UpdateSecurityStampAsync(user);         var result = await _signInManager.SignInAsync(user, isPersistent: false);         // handle `SignInResult` cases     } } 

By updating the security stamp will cause all existing auth cookies to be invalid, basically logging out all other devices where the user is logged in. Then, you sign in the user on this current device.

Answers 3

Best way is to do something similar to what Google, Facebook and others do -- detect if user is logging in from a different device. For your case, I believe you would want to have a slight different behavior -- instead of asking access, you'll probably deny it. It's almost like you're creating a license "per device", or a "single tenant" license.

This Stack Overflow thread talks about this solution.

The most reliable way to detect a device change is to create a fingerprint of the browser/device the browser is running on. This is a complex topic to get 100% right, and there are commercial offerings that are pretty darn good but not flawless.

Note: if you want to start simple, you could start with a Secure cookie, which is less likely to be exposed to cookie theft via eavesdropping. You could store a hashed fingerprint, for instance.

Answers 4

There are some access management solutions (ForgeRock, Oracle Access Management) that implement this Session Quota functionality. ForgeRock has a community version and its source code is available on Github, maybe you can take a look at how it is implemented there. There is also a blog post from them giving a broad view of the functionality (https://blogs.forgerock.org/petermajor/2013/01/session-quota-basics/)

If this is too complex for your use case, what I would do is combine the "shared memory" approach that you described with an identity function, similar to what Fabio pointed out in another answer.

Read More

Wednesday, September 12, 2018

How to combine the windows authentication and JWT with .Net Core 2.1

Leave a Comment

I have tried to use the windows authentication and JWT together with .NET Core 2.1.

I have following startup settings of the authentication:

services.AddAuthentication(options =>                 {                     options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;                     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;                 })                 .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>             {                 options.TokenValidationParameters = new TokenValidationParameters                 {                     ValidateIssuer = true,                     ValidateAudience = true,                     ValidateLifetime = true,                     ValidateIssuerSigningKey = true,                      ValidIssuer = "Test",                     ValidAudience = "Test",                     IssuerSigningKey = JwtSecurityKey.Create("677efa87-aa4d-42d6-adc8-9f866e5f75f7")                 };                  options.Events = new JwtBearerEvents()                 {                     OnAuthenticationFailed = OnAuthenticationFailed                 };             }); 

IIS settings:

"iisSettings": {     "windowsAuthentication": true,      "anonymousAuthentication": true,      ..   } 

I have tried following code snippet to create the JWT token with windows authentication:

[Route("api/[controller]")]     [ApiController]     [Authorize(AuthenticationSchemes = "Windows")]     public class AuthController : ControllerBase     {         [HttpPost("token")]         public IActionResult Token()         {             //Setup claims             var claims = new[]             {                 new Claim(ClaimTypes.Name, User.Identity.Name),                 //Add additional claims             };              //Read signing symmetric key             var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("677efa87-aa4d-42d6-adc8-9f866e5f75f7"));             var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);              //Create a token             var token = new JwtSecurityToken(                 issuer: "Test",                 audience: "Test",                 claims: claims,                 expires: DateTime.Now.AddMinutes(30),                 signingCredentials: creds);              //Return signed JWT token             return Ok(new             {                 token = new JwtSecurityTokenHandler().WriteToken(token)             });         }     } 

And in another controller I need use only JWT authentication:

[Route("api/[controller]")]     [ApiController]     [Authorize(AuthenticationSchemes = "Bearer")]     public class ProductController : ControllerBase     {         [HttpGet]         public IActionResult Get()         {             var userName = User.Identity.Name;              var claims = User.Claims.Select(x => new { x.Type, x.Value });              return Ok(new { userName, claims });         }     } 

If the JWT token is expired then I correctly received the response code 401 but I still get the dialog in the browser for putting the credentials.

How can I configure the windows authentication only for a part when I want to create the JWT token and disable response which is responsible for showing the browser dialog with credentials? How to correctly combine these things?

1 Answers

Answers 1

This answer might help: https://stackoverflow.com/a/51055082/1212994

You need to ensure, that you NOT setting Authorization: Bearer HTTP header when you trying to use Windows Auth. The key point here is how "Windows Auth" actually works. Let's look how it works with browser for example.

Read More

Monday, August 27, 2018

Splitting a string throws InvalidOperationException when hosting on IIS

Leave a Comment

I wrote the following code:

private string makeMailContents(Klant klant, Mail mail) {     var builder = new BodyBuilder();     var path = Path.Combine("wwwroot/trackers/track_open.png");     var img = builder.LinkedResources.Add(path);     byte[] data = Convert.FromBase64String(mail.Content);     string decoded = Encoding.UTF8.GetString(data);     string code;     string final = "";     Regex regex = new Regex(@"\[([^]]*)\]");      img.ContentId = MimeUtils.GenerateMessageId();      var splitContent = decoded.Split(' ');      foreach(string word in splitContent) // this is line 265     {              if (word.Contains('[') && word.Contains(']'))             {                 try                 {                     code = Regex.Match(word, @"\[([^]]*)\]").Groups[1].Value.ToLower();                     switch (code)                     {                         case "voornaam":                             final += regex.Replace(word, klant.vnaam) + ' ';                             break;                         case "achternaam":                             final += regex.Replace(word, klant.anaam) + ' ';                             break;                         case "naam":                             final += regex.Replace(word, klant.vnaam + ' ' + klant.anaam + ' ');                             break;                         case "onderwerp":                             final += regex.Replace(word, mail.Onderwerp + ' ');                             break;                         case "datum":                             final += regex.Replace(word, DateTime.Now.ToString("dd-MM-yyyy") + ' ');                             break;                     }                 }                 catch (Exception ex)                 {                     final += ex;                 }             }             else             {                 final += word + ' ';             }     } } 

Whenever I run this code on my local machine and my test server it executes the code like it should without any exceptions.

But whenever I host this on my current live server it throws the following exception:

InvalidOperationException: Sequence contains no elements

And this exceptions keeps pointing towards the splitContent and it tells me that it doesn't contain elements. And yes, the mail.Content is filled with a valid base64 string, I checked both with fiddler and postman.

Does anyone have the slightest clue of what's going on here? I'm also not sure if it's the IIS settings or somehow my code. I normally have a colleague who manages the IIS but he is on vacation right now. Can someone help me out with this?

This is the data the mail receives when called:

 {           "Onderwerp":"Dit is een test campagne",     "afzender":1,     "campagne":1,     "Content":"PHA+RGl0IGlzIGVlbiB0ZXN0IG1hYXQ8L3A+Cg==",     "docs":"['kamer2.jpg']",     "template":null,     "verzenddat":"8/17/18, 3:55 PM" } 

full exception:

System.InvalidOperationException: Sequence contains no elements    at System.Linq.Enumerable.Last[TSource](IEnumerable`1 source)    at lambda_method(Closure , QueryContext )    at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass17_1`1.<CompileQueryCore>b__0(QueryContext qc)    at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)    at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)    at System.Linq.Queryable.Last[TSource](IQueryable`1 source)    at MailerAPI.Mailer.Sender.makeMailContents(Klant klant, Mail mail) in C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Mailer\Sender.cs:line 265    at System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)    at MailerAPI.Mailer.Sender.<sendMessage>d__7.MoveNext() in C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Mailer\Sender.cs:line 161 --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at MailerAPI.Controllers.MailController.<Post>d__13.MoveNext() in C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Controllers\MailController.cs:line 96 --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeNextResourceFilter>d__22.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext() --- End of stack trace from previous location where exception was thrown ---    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext() 

The exception also gets thrown when I replace the model properties with just a plain string.

UPDATE Whenever I run this code in my values controller to test the decoded.split(' ') it actually works. When I return the decoded.split(' ') I actually get an array of strings.

So now I know that the problem only occurs within the method, which is located in a Sender class and being called in the MailerController, and it also only occurs in the current server.

1 Answers

Answers 1

You appear to be making a call to .Last() at or through the code located at C:\Users\Hofkey\Source\Repos\MailerAPI\MailerAPI\Mailer\Sender.cs:line 265.

The Linq extension method .Last() demands that there is at least one item that it can grab. To work around this requirement, you have various options:

  • use .LastOrDefault() accompanied with appropriate null handling, or
  • before using .Last(), first check with if (... .Any()) if it is OK to call .Last().


For further reference, see LINQ Element Operations

Read More

Friday, July 20, 2018

Registering Actions for ControllerModel in ASP.NET Core

Leave a Comment

I am trying to add a new ActionModel for a ControllerModel in an implementation of IControllerModelConvention, but I cannot find any documentation or examples of how this model system works or how to do this correctly. I am able to add a new ActionModel easily enough, but it is not routable once the application is running:

var action = new ActionModel(method, new object[] { new HttpGetAttribute("/test") }) {     Controller = controller,     ActionName = "test" }; controller.Actions.Add(action); 

It seems I need to add a selector to the action, perhaps other properties as well, but I haven't been able to find one that exposes this action. Also unsure if my attributes are correct/redundant. Ultimately I would like to add multiple actions that do not map 1:1 to the methods in the controller.

1 Answers

Answers 1

I've made it work similiar to your approach. Maybe this can help you:

Controller

public class TestController : Controller {     public IActionResult Index()     {         return Ok(new string[] { "Hello", "World" });     } } 

Model Convention

public class TestControllerModelConvention : IControllerModelConvention {     public void Apply(ControllerModel controller)     {         Type controllerType = typeof(TestController);         MethodInfo indexAction = controllerType.GetMethod("Index");          var testAction = new ActionModel(indexAction, new[] { new HttpGetAttribute("/test") })         {             ActionName = "Index",             Controller = controller         };         controller.Actions.Add(testAction);     } } 

Startup

public void ConfigureServices(IServiceCollection services) {     // other initialitation stuff      services.AddMvc(options =>     {         options.Conventions.Add(new TestControllerModelConvention());     }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } 

Now when I start the application and browse "/test" it will hit the controller action.

Read More

Monday, July 2, 2018

Restore AJAX handling for ASP.NET Core to previous functionality

Leave a Comment

In previous MVC5 and below, you could make an ajax call that unwrapped the parameters properly:

JS:

$.post('/controller/endpoint',{intparam: 1, strparam: 'hello'}) 

CS:

public ActionResult endpoint(int intparam, string strparam){} 

In the new aspnetcore, it has changed:

CS:

public CustomClassWrapper{      public int intparam {get;set;}     public string stringparam {get;set;} } public ActionResult endpoint([FromBody]CustomClassWrapper item){} 

To sum it up, in the new framework, you need to write a wrapper class and can only pass one [FromBody] parameter to the method. Previously, the params would be unwrapped by variable name correctly.

So, i'm trying to re-implement this functionality in an aspnetcore middleware component. I'm having difficulty in how to accomplish calling the controller method properly with the parameters.

My current cut-down code:

public async Task Invoke(HttpContext context)         {             if (IsAjaxRequest(context.Request))             {                 try                 {                     string bodyContent = new StreamReader(context.Request.Body).ReadToEnd();                     var parameters = JsonConvert.DeserializeObject(bodyContent);                     ///What to do here?                 }                 catch (Exception ex)                 {                     throw new Exception("AJAX method not found ", ex);                 }             }             else             {                 await _next(context);             }         } 

I'm really just not sure about what to do after deserializing the parameters. I have the URL for the endpoint and also the params correctly. Just need to know how to call the method and return the result as JSON. Should i be using Reflection to get the controller method? Or is there a better way using MVC?

2 Answers

Answers 1

it's very simple thing i don't know why it not working at your end

JS

$.post('actionMethodURl', { FirstName: '1', LastName: 'hello' }).done(Successfunction); 

CS

[HttpPost] public ActionResult endpoint(string FirstName,string LastName) {   object Message = string.Empty;   if (ModelState.IsValid)    {      Message = "Pass";    }    else    {    Message = ModelState.Errors();    }    return Json(Message); } 

MyJSCode MyActionMetho

Answers 2

Try implement custom IModelBinder.

public class BodyFieldModelBinder : IModelBinder {     public Task BindModelAsync(ModelBindingContext bindingContext)     {         bindingContext.HttpContext.Request.EnableRewind(); // required to read request body multiple times         var inputStream = bindingContext.HttpContext.Request.Body;         if (inputStream.Position != 0L)             inputStream.Position = 0;         var bodyValue = new StreamReader(inputStream, Encoding.UTF8).ReadToEnd();         var jsonObject = (JObject)JsonConvert.DeserializeObject<object>(bodyValue);         if (jsonObject.TryGetValue(bindingContext.FieldName, out var jToken))         {             var jsonSerializer = JsonSerializer.Create();             var result = jToken.ToObject(bindingContext.ModelType, jsonSerializer);             bindingContext.Result = ModelBindingResult.Success(result);             return Task.CompletedTask;         }         bindingContext.Result = ModelBindingResult.Failed();         return Task.CompletedTask;     } } 

Be careful, the code above lacks error handling and etc.

And use it like this:

[HttpPost] public IActionResult Endpoint([ModelBinder(typeof(BodyFieldModelBinder))] int intparam) 

Also you could implement custom attribute to reduce complexity of declaration:

public class BodyFieldAttribute : ModelBinderAttribute {     public BodyFieldAttribute()         : base(typeof(BodyFieldModelBinder))     {     } } 
Read More

Monday, June 25, 2018

.net core perf profiler via code

Leave a Comment

I developed a middleware that starts a Stopwatch before invoking next and stops when the response is available, I do log the elapsed time after that.

This is all good. But it doesnt provide me breakdown, ie: within the call which method invocations took how much? for example: if I have 4 method calls in a request, I would like to know each one's duration.

I assume, middleware is not enough for this purpose, without having to put decorators all over the place, how can i get this done?

Thanks.

1 Answers

Answers 1

Probably, you have to manually instrument most interesting pieces of code.

Although, there are solutions for IL injection (see MSIL Injection page on PostSharp website), I don't think that it is possible to inject code in arbitrary places without changing existing code base. However, in many cases it is relatively easy to instrument large portion of existing code (given it is reasonably well separated into modules) using decorators. For example add custom profiling DelegatingHandler to HttpClient or use profiling SqlConnection factory.

In order to inspect call hierarchy and latency you can utilize MiniProfiler, it's built-in decorators and RenderPlainText() method. Or you can utilize Metrics.NET library to inspect throughput related metrics such as histogram and counter.

Read More

Wednesday, June 6, 2018

MVC Print Page break not working, contents are cut off

Leave a Comment

I tried below code to break the page while printing however its not working, I learnt that the Page break won't work in nested div tags, I 'm not sure how to achieve this, basically I 'm trying to display images, so in a row there will be 4 or more than that based on the display size of screen however at the time of printing it should print 4 images in a row and the next 4 images should be printed in next page as if now while printing, the images and the contents are getting cut off, please help

     <div class='row small'>         @foreach (var item in Model.BuyerList.ImageList)         {              <div class="card bg-light mb-3 mr-1 card-text-fixed-width" style='page-break-after:always'>                 <div class="img-control">                     @if (!string.IsNullOrWhiteSpace(item.ImageUrl))                     {                         <img src="@item.ImageUrl" style="height:150px;" class="card-img-top" alt="Card image" />                     }                     else                     {                         <img src="~/AdTrack Images/NoProductImage.png" style="height:150px;" class="card-img-top" alt="Card image" />                     }                       <div class="edit d-print-none">                             <a data-toggle="modal"                                data-id='{"id": "@item.Items.Number","ItemId":"@item.Items.ItemId", "AdId":"@item.Header.Id"}'                                class="open-AddBookDialog btn btn-primary" href="#"><i class="fa fa-pencil fa-lg"></i></a>                         </div>                          <div class="delete d-print-none">                             <a data-toggle="modal" data-id='{"id": "@item.Items.Number","ItemId":"@item.Items.Id", "AdId":"@item.Id"}'                                class="open-delete btn btn-primary" href="#">                                 <i class="fa fa-trash" style="font-size:15px;color:red" id="delete" name="delete"></i>                             </a>                         </div>                          <div class="edit d-print-none">                             <a data-toggle="modal"                                data-id='{"id": "@item.Items.Number","ItemId":"@item.Items.ItemId", "AdId":"@item.Header.Id"}'                                class="open-AddBookDialog btn btn-primary" href="#"><i class="fa fa-info-circle fa-lg"></i></a>                         </div>                     }                 </div>                 <div class="card-header">                     <div class="font-weight-bold">Page @Html.DisplayFor(modelItem => item.Number)- @Html.DisplayFor(modelItem => item.Business)</div>                     <div class="row mb-2 font-weight-bold">                         <div class="col-md-6">Cut: @Html.DisplayFor(modelItem => item.Items.Number)</div>                         <div class="col-md-6 text-right">9-Box: @Html.DisplayFor(modelItem => item.Items.BoxNumber)</div>                     </div>                     <div class="row mb-2 font-weight-bold">                         <div class="col-md-4">Group @Html.DisplayFor(modelItem => item.Department.Test)</div>                         @*<div class="col-md-4">Div: @Html.DisplayFor(modelItem => item.Department.Division)</div>*@                         <div class="col-md-4">Buyer @Html.DisplayFor(modelItem => item.Department.Test)</div>                         <div class="col-md-4">Dept @Html.DisplayFor(modelItem => item.Items.Department)</div>                     </div>                 </div>  </div>         }         </div> 

1 Answers

Answers 1

Add wrap div with style='page-break-after:always'.

<div class='row small'>         @foreach (var item in Model.BuyerList.ImageList)         {             <div style='page-break-after:always'>                 <div class="card bg-light mb-3 mr-1 card-text-fixed-width" >                     <div class="img-control">                         @if (!string.IsNullOrWhiteSpace(item.ImageUrl))                         {                             <img src="@item.ImageUrl" style="height:150px;" class="card-img-top" alt="Card image" />                         }                         else                         {                             <img src="~/AdTrack Images/NoProductImage.png" style="height:150px;" class="card-img-top" alt="Card image" />                         }                           <div class="edit d-print-none">                                 <a data-toggle="modal"                                    data-id='{"id": "@item.Items.Number","ItemId":"@item.Items.ItemId", "AdId":"@item.Header.Id"}'                                    class="open-AddBookDialog btn btn-primary" href="#"><i class="fa fa-pencil fa-lg"></i></a>                             </div>                              <div class="delete d-print-none">                                 <a data-toggle="modal" data-id='{"id": "@item.Items.Number","ItemId":"@item.Items.Id", "AdId":"@item.Id"}'                                    class="open-delete btn btn-primary" href="#">                                     <i class="fa fa-trash" style="font-size:15px;color:red" id="delete" name="delete"></i>                                 </a>                             </div>                              <div class="edit d-print-none">                                 <a data-toggle="modal"                                    data-id='{"id": "@item.Items.Number","ItemId":"@item.Items.ItemId", "AdId":"@item.Header.Id"}'                                    class="open-AddBookDialog btn btn-primary" href="#"><i class="fa fa-info-circle fa-lg"></i></a>                             </div>                         }                     </div>                     <div class="card-header">                         <div class="font-weight-bold">Page @Html.DisplayFor(modelItem => item.Number)- @Html.DisplayFor(modelItem => item.Business)</div>                         <div class="row mb-2 font-weight-bold">                             <div class="col-md-6">Cut: @Html.DisplayFor(modelItem => item.Items.Number)</div>                             <div class="col-md-6 text-right">9-Box: @Html.DisplayFor(modelItem => item.Items.BoxNumber)</div>                         </div>                         <div class="row mb-2 font-weight-bold">                             <div class="col-md-4">Group @Html.DisplayFor(modelItem => item.Department.Test)</div>                             @*<div class="col-md-4">Div: @Html.DisplayFor(modelItem => item.Department.Division)</div>*@                             <div class="col-md-4">Buyer @Html.DisplayFor(modelItem => item.Department.Test)</div>                             <div class="col-md-4">Dept @Html.DisplayFor(modelItem => item.Items.Department)</div>                         </div>                     </div>                 </div>             </div>         }         </div> 
Read More

Sunday, June 3, 2018

SignalR Core not generating(mapping) Client methods

Leave a Comment

The SignalR Core is generating Hub proxies script, but not adding the "client" methods. (No errors in server or client - only not working)

Generated JS from <script src="http://localhost/signalr/hubs">

proxies['messageHub'] = this.createHubProxy('messageHub');  proxies['messageHub'].client = { }; proxies['messageHub'].server = {         handleMessage: function (receivedString) {             return proxies['messageHub'].invoke.apply(proxies['messageHub'], $.merge(["HandleMessage"], $.makeArray(arguments)));          }     }; 

Here's the Hub in Server Side:

public class MessageHub : Hub {     public void HandleMessage(string receivedString)     {         var responseString = string.Empty;          MessageHandler.HandleMessage(receivedString, ref responseString);          Clients.All.sendMessage(responseString);      } } 

The sendMessage methos should be included in the messageHub client proxies in the JS file. $.connection.messageHub.client.sendMessage is undefined

Only the handleMessage for server proxies was created (and working).

Here's my StartUp.cs inclusions for SignalR:

ConfigureServices:

services.AddMvc(options =>         {             options.Filters.Add(new RoleFilterAttribute());         }).AddJsonOptions(options => options.SerializerSettings.ContractResolver =                 new DefaultContractResolver()); services.AddSignalR(options => options.Hubs.EnableDetailedErrors = true) 

Configure:

app.UseWebSockets(); app.UseSignalR(); 

project.json:

"Microsoft.AspNetCore.Mvc": "1.0.0-*", "Microsoft.AspNetCore.WebSockets": "1.0.0", "Microsoft.AspNetCore.SignalR.Server": "0.2.0-*", 

SOME ADDITIONAL TENTATIVES:

1 - Change method case in Server Side to see if it's mapped:

Clients.All.SendMessage(responseString); 

Did not work!

2 - Change the client side to dynamic mapping:

var connection = $.hubConnection('http://localhost/'); var proxy = connection.createHubProxy('messageHub'); connection.start({ withCredentials: false }).done(function () { console.log("CONNECTED") }); proxy.on("sendMessage", function (result) {console.log(result);}); proxy.invoke("handleMessage", msg).done(function(result)console.log(result);}); 

Again only the handleMessage (server) worked.

0 Answers

Read More

Monday, April 16, 2018

Maximum concurrent requests in signalr self hosted in kestrel

Leave a Comment

I've encountered a strange problem with an application I've developed. The application is a windows service hosting AspNetCore 2.0 running on Kestrel. This application receives requests through an IIS site acting as a proxy.

In this application, I also use signal 2.2.2 integrated using Microsoft.AspNetCore.Owin. All worked well until I detected that the application was not responding to requests.

Other applications on the same machine and using the same IIS server as proxy were working fine. Restarting the application pool serving the site solved the problem temporarily.

The problem resurfaced again and digging through monitoring information the application seems to hang when there are 400 signalr SSE connections on the same machine. This seems plausible as I've found that by default OWIN limits the number of concurrent requests at 100 * number of cpus. (Note that a site on the same machine is serving 5000 requests per minute without a sweat but these are not a long-lived request like the SignalR ones)

The problem is that I seem unable to find the same option when hosting Owin inside AspNetCore. Does someone know if this can be the solution and what is the correct setting?

EDIT: I'm fairly certain that the issue is caused by the number of SignalR connections opened concurrently because by disabling it in Javascript the problem vanished.

2nd EDIT: signalr does not seem to be the cuplrit as load testing the site with crank both in test and in production worked until 5000 concurrent connections which is the default IIS limit and is fine by me

1 Answers

Answers 1

This could be the issue, but it's unlikely. When hosting in dotnet core you're probably using Kestrel as a webserver implementation, to switch these limits such as concurrent connections you can use KestrelServerLimits class as described in this Microsoft article.

KestrelServerLimits should not be causing you any problems since the default value for ConcurrentConnections is unlimited.

Read More

Wednesday, April 11, 2018

LinkedIn authentication stopped returning formatted picture

Leave a Comment

My app uses LinkedIn authentication along with a couple of other social network logins.

Even though authentication is working fine, all of a sudden LinkedIn stopped returning the formatted profile picture i.e. picture-url. I do however continue to receive the original image i.e. picture-urls -- see below: enter image description here

In my authentication request, I request r_basicprofile and r_emailaddress and according to this link, I should be receiving both the formatted and the original image. https://developer.linkedin.com/docs/fields/basic-profile

Up until 10 days ago or so, I was receiving both images. I didn't make any changes to my code but for some reason, the formatted image doesn't show up anymore. Any idea why and how to fix this?

UPDATE: All of a sudden I started getting both images again -- without making any changes to my code.

I also noticed that the image URL has now changed and I'm seeing all types of parameters in there -- such as image size, something that looks like API version type (alpha in the example below) and possibly a time stamp indicator:

https://media.licdn.com/dms/image/{image-id}/profile-displayphoto-shrink_100_100/0?e=123456789&v=alpha&t={sometypeofid} 

I don't remeber seeing any of these parameters in the image URL which is not a URL at all but what seems to be an API call that returns an image.

I don't know if LinkedIn announced such changes that I missed or just decided to make these changes without keeping developers in the loop. I hope it's not the latter and I simply missed the announcement.

0 Answers

Read More

Friday, April 6, 2018

ASP .NET Core 2.0, SignalR

Leave a Comment

I have a SignlaR server in ASP .NET Core 2.0 application hosted in Windows AZURE:

public class Chat : Hub {     public Task Send(string message)     {         return Clients.All.InvokeAsync("Send", message);     } } 

I also have client in Javascript:

<script src="scripts/signalr-client.min.js"></script> connection.on('send', data => {     console.log(data); });  connection.start()           .then(() => connection.invoke('send', 'Hello')); 

It works fine but how to connect this server in Python Script? There is the library: https://pypi.python.org/pypi/signalr-client/0.0.6

But doesn't work. I have an error:

signalr/negotiate 404 (not found) 

Python code:

from requests import Session from signalr import Connection  with Session() as session:     #create a connection     connection = Connection("wss://wg2.azurewebsites.net", session)      #get chat hub     chat = connection.register_hub("deviceshub")      #start a connection     connection.start() 

Can you provide a working sample (Python client) with ASP .NET Core 2.0?

3 Answers

Answers 1

The python library you are using seems to be for the previous version of SignalR. SignalR for Asp.NET Core is not compatible with the previous version of SignalR so the old client will not work with the new server (or vice versa).

Answers 2

I have some suggestions which you can check:

Option 1
Stop using the SSL version and check if it works. Because at your Javascript function you use ws://" + window.location.host + "/chat

wss:// to ws:// 

Option 2
If I go to your domain wg2.azurewebsites.nl I get the following error:

Failed to load https://wg2.azurewebsites.net/deviceshub: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://wg2.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 404. 

Which means your server needs to respond a Access-Control-Allow-Origin header with the domain name.

Option 3
In your javascript you connect to /chat where now you try to connect to /deviceshub maybe it does not exist. So change to chat

Answers 3

As you you are getting 404 error .

signalr/negotiate 404 (not found)

And in the python code,you are connecting to deviceshub

#get chat hub chat = connection.register_hub("deviceshub")

Shouldn't you be connecting to chathub ?

chat = connection.register_hub("chat")

If this does not help,double check the request send from python app.

If signalr connection gets successfull,you should see a url going like

https://example.com/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1522732715296

double check the hostname and full url part if it is same as in the javascript client.

Hope this helps!

Read More

Friday, March 23, 2018

Response.TrySkipIisCustomErrors equivalent for asp.net core?

Leave a Comment

How to prevent IIS from overriding custom error pages with IIS default error pages? Is there a Response.TrySkipIisCustomErrors equivalent for asp.net core? In ASP Net MVC I use the code below to send error without a custom page but in asp net core it is not working.

try {     // some code } catch (Exception ex) {     Response.TrySkipIisCustomErrors = true;     Response.StatusCode = (int)HttpStatusCode.InternalServerError;     mensagem = ex.Message; } 

1 Answers

Answers 1

What you can try is writing an exception handling middleware. Here is a blog post which I have used for reference. Something along the lines of

    public class ErrorHandlingMiddleware     {       private readonly RequestDelegate next;        public ErrorHandlingMiddleware(RequestDelegate next)       {         this.next = next;       }        public async Task Invoke(HttpContext context)       {         try         {             await next(context);         }         catch (Exception ex)         {             await CustomHandleExceptionAsync(context, ex);         }       }      private static Task CustomHandleExceptionAsync(HttpContext context, Exception exception)     {          if (exception is NotFoundException)         {           var customJson = JsonConvert.SerializeObject(new{ error =           exception.Message });          context.Response.ContentType = "application/json";          context.Response.StatusCode = (int)HttpStatusCode.NotFound;          return context.Response.WriteAsync(customJson);        }    } 
Read More

Thursday, March 22, 2018

One MVC web application as API and client

Leave a Comment

I have an MVC web app, and a WPF client and Web API server. I would very much like to pull the API controllers into the MVC app, and have only one app/api. My main reason for this is to have one sign-in procedure for application users and API clients alike.

What I would have liked to do is inject a SignInManager<ApplicationUser into the Token controller and use

var result = await _signInManager.PasswordSignInAsync(login.Username, login.Password, false, false); 

to authenticate the username and password using the same password hasher as build into the MVC project. I don't want to duplicate any of that type of functionality. I also hope, with this, to achieve a sign-in that gives a JWT token, for the WPF app to access the API side of things, and a standard signed-in cookie, for normal MVC app requests to be authorized.

How should I go about this with minimum code duplication?

IDEA: Use one MVC application as a REST server as well. If my Login action that gets the JWT also signs me in, e.g. with _signInManager.PasswordSignInAsync, I should also get the cookie that will allow me to access protected actions internally, and use them externally with the authorization header containing the JWT.

1 Answers

Answers 1

You can consider the following options

Option #1: Move the logic which is used in MVC app to new class library which then can be referenced by API project. This will allow you to follow SRP and use the same logic in both MVC and API apps. If you want to make ASP.NET Identity related functionality to be common for MVC and API apps take a look at Moving ASP.NET Identity Model to Class Library and follow provided steps.

Option #2: You can move all controllers and models from API to MVC app. You can configure then API controllers to use JWT authentication scheme and continue using cookie authentication scheme fr MVC apps' controllers. If you want to follow this approach you will need to configure your Authentication middleware. For example your Startup class would look something like this:

public void ConfigureServices(IServiceCollection services) {     ...     services.AddMvc();      services.AddAuthentication(o =>     {         o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;         o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;         o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;     }).AddCookie(options =>     {         options.AccessDeniedPath = new PathString("/Account/Login/");         options.LoginPath = new PathString("/Account/Login/");     }).AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => {             options.TokenValidationParameters = new TokenValidationParameters {...};     }); }  public void Configure(IApplicationBuilder app, IHostingEnvironment env) {     ...     app.UseAuthentication();     app.UseMvcWithDefaultRoute();     ... }     

Then you can define BaseApiController which can be used to setup a route to API controllers and authorize them using e.g.

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] [Route("api/[controller]")] public abstract class BaseApiController {} 

and make all API controllers inherit this base controller. You can also use policy based authorization which is more flexible. After you accomplish you will be able to authenticate with cookie in MVC app controllers and with JWT token in API controllers.

Option #3: You can leave API and MVC app running separately and use IdentityServer to implement OAuth protocol. Add it to MVC app since it integrates well with ASP.NET Identity and configure it so that to continue using the cookie authentication scheme for MVC app. Then configure one of the OAuth flow to setup the authorization between WPF app and API. IdentityServer is well documented and provides samples for different flows in their GitHub. The advantage of this approach is that you will never have such problem in future even if you consider adding more APIs, SPA or MVC apps which will have to use the same user base. Also it allows to implement Single Sign On(SSO) so if you ever need another MVC app it will be easy integrate it into existing infrastructure.

Read More

Sunday, February 25, 2018

ASP .NET Core 2.0, SignalR

Leave a Comment

I have SignlaR server in ASP .NET Core 2.0 application hosted in Windows AZURE:

public class Chat : Hub {     public Task Send(string message)     {         return Clients.All.InvokeAsync("Send", message);     } } 

I also have client in Javascript:

<script src="scripts/signalr-client.min.js"></script> connection.on('send', data => {     console.log(data); });  connection.start()           .then(() => connection.invoke('send', 'Hello')); 

It works fine but how to connect this server in Python Script? There is library: https://pypi.python.org/pypi/signalr-client/0.0.6

But doesn't work. I have error:

signalr/negotiate 404 (not found) 

Python code:

from requests import Session from signalr import Connection  with Session() as session:     #create a connection     connection = Connection("wss://wg2.azurewebsites.net", session)      #get chat hub     chat = connection.register_hub("deviceshub")      #start a connection     connection.start() 

Can you provide working sample (Python client) with ASP .NET Core 2.0?

1 Answers

Answers 1

I have some suggestions which you can check:

Option 1
Stop using the SSL version and check if it works. Because at your Javascript function you use ws://" + window.location.host + "/chat

wss:// to ws:// 

Option 2
If I go to your domain wg2.azurewebsites.nl I get the following error:

Failed to load https://wg2.azurewebsites.net/deviceshub: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://wg2.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 404. 

Which means your server needs to respond a Access-Control-Allow-Origin header with the domain name.

Option 3
In your javascript you connect to /chat where now you try to connect to /deviceshub maybe it does not exist. So change to chat

Read More

Thursday, February 8, 2018

ASP.NET Core jquery Autocomplete returns blank lines in the list

Leave a Comment

I am using ASP.NET Core jquery Autocomplete with Boostrap 4 I have successfully run the following example from : https://jqueryui.com/autocomplete/

I am now looking to use data from my controller which returns data properly. The result that I get is blank lines.

enter image description here

Here is my Razor page

<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">  <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>  <div class="ui-widget">     <label>Autocomplete Example: </label>     <input id="LastName" name="LastName" type="text" /> </div> <script>     $("#LastName").autocomplete({         source: '@Url.Action("GetName","Home")'     }); </script> 

Here's my controller [HttpGet] public IActionResult GetName(string term) {

        List<TransactionName> list = new List<TransactionName>()         {              new TransactionName {Id=1,LastName="Linda" },             new TransactionName {Id=2,LastName="Donna" },             new TransactionName {Id=3,LastName="Maryanne" },             new TransactionName {Id=4,LastName="Deb" },             new TransactionName {Id=5,LastName="Liz" },             new TransactionName {Id=6,LastName="Bobby" },             new TransactionName {Id=7,LastName="Beth" }      };         var result = (from N in list                         where N.LastName.Contains(term)                         select new {N.LastName });         return Json(result);     } 

enter image description here

2 Answers

Answers 1

I changed the following based on the jquery Autocomplete documentation:

    var result = (from N in list                     where N.LastName.Contains(term)                     select new {value=N.LastName }); 

Here's a portion of the documentation taken from their site. Multiple types supported: Array: An array can be used for local data. There are two supported formats: An array of strings: [ "Choice1", "Choice2" ] An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

Answers 2

Your result is returning to your browser as:

{     "Linda",     "Donna",     //... etc } 

What you actually want to return is:

[     "Linda",     "Donna",     //... etc ] 

To do this, simply change your return line to this:

return Json(result.ToArray());

If this does not work, use browser developer tools to inspect your returned result and modify your return line to format the output as the autocomplete method requires.

Read More

Monday, December 18, 2017

.net Core MVC: X-SRF-TOKEN not accepted, 400 returned

Leave a Comment

I have a .net core app using angularJS, and I want to protect the api calls protected by our cookie based authentication. I Followed the steps in this article:

https://docs.microsoft.com/en-us/aspnet/core/security/anti-request-forgery

  • I added the services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN"); to my services configuration
  • I am seeing the XSRF-TOKEN cookie in my developer tools when loading the page.
  • I am seeing the X-XSRF-TOKEN header being added to my $http sent requests.

  • I have added the [AutoValidateAntiforgeryToken] to my controller that is handling the ajax request.

  • I have ssl enabled, and am accessing the pages via https.

I can make GET requests fine through this api endpoint as expected. However, I am receiving a 400 error without any details of why the request was bad on PUTs and POSTs.

I know the X-XSRF-TOKEN is on the request, (seen in the network tab of chrome dev tools) so I am unsure what I am missing to allow these requests to be received correctly.

TL;DR: Why is .net core rejecting my valid AntiforgeryToken?

UPDATE Attempted @joey's suggested solution, but it did not work, still receiving 400 responses. code below reflects another solution I tried to fix this problem (aka angularjs's solution to setting default cookies and headers for cross site scripting protection)

I have also attempted to configure AngularJS to change what the cookie and header names match what I configured in my Startup.cs. I changed their names to try both XSRF-TOKEN (cookie) and X-XSRF-TOKEN (header) as well as CSRF-TOKEN and X-CSRF-TOKEN, and while the configurations within angular is correctly using the new default to what ever I provide, my authentication code in .net core is still not working.

for more information here is how i am configuring AngularJS:

app.config(function ($httpProvider) {     $httpProvider.defaults.xsrfHeaderName = 'X-CSRF-TOKEN';     $httpProvider.defaults.xsrfCookieName = 'CSRF-TOKEN'; }); 

here is the ConfigureServices line I have in my Startup.cs file:

services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN"); 

and lastly here is the code I added to the Configure method of the Startup.cs file:

    app.Use(next => context =>      {         string path = context.Request.Path.Value;         if (path.Contains("/MyProtectedPath/"))         {             var tokens = antiforgery.GetAndStoreTokens(context);             context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken,                 new CookieOptions { HttpOnly = false });         }         return next(context);     }); 

UPDATE 2: I have added the following to my controller action:

if (HttpContext.Request.Method.ToLower(CultureInfo.InvariantCulture) != "get") {     await _antiforgery.ValidateRequestAsync(HttpContext); } 

AntiforgeryValidationException: The provided antiforgery token was meant for a different claims-based user than the current user.

I thought maybe antiforgery.GetAndStoreTokens(context) might be overriding the current cookie sent on the page load, so I make it only hit that code on GET requests, but I get the same result for the posts.

2 Answers

Answers 1

In the code you have posted, you are adding the header X-XSRF-TOKEN, but the header should be X-CSRF-TOKEN.

The example from the web page you linked provides the example:

services.AddAntiforgery(options => options.HeaderName = "X-CSRF-TOKEN");  

Update:

Thanks for clarifying with the additional code & information. The means of implementing CSRF selected here is one which passes the token as a header on the response of the initial HTML file. Here is an example of how such a case might be configured for a SPA web application:

app.Use(next => context => {     string path = context.Request.Path.Value;     if (         string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||          string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase)     )     {         var tokens = antiforgery.GetAndStoreTokens(context);         context.Response.Cookies.Append("CSRF-TOKEN", tokens.RequestToken,              new CookieOptions() { HttpOnly = false });     }      return next(context); }); 

However, with your service configured to using the String.Contains method [1], antiforgery.GetAndStoreTokens(context) is invoked for any path containing /MyProtectedPath/ anywhere. This means it has been configured in such a way that matches not only /MyProtectedPath/, but also /MyProtectectedPath/a/b/c or /a/b/c/MyProtectedPath/.

To check the CSRF token sent in subsequent requests of an applicable HTTP method as shown below:

if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase)) {     await antiforgery.ValidateRequestAsync(context);     // The line above will throw if the CSRF token is invalid. } 

If the method GetAndStoreTokens is called before this for any matching path, the token will be overwritten before it is checked, which is why .net examples will typically order GetAndStoreTokens first, but with the specific condition for looking at the path and HTTP method.

[1] https://msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx

Answers 2

Joey's answer seems to be right. But since you've mentioned it doesn't work for you here's what I had to do to get it working.

First, from the docs:

AngularJS uses a convention to address CSRF. If the server sends a cookie with the name XSRF-TOKEN, the Angular $http service will add the value from this cookie to a header when it sends a request to this server. This process is automatic; you don't need to set the header explicitly. The header name is X-XSRF-TOKEN. The server should detect this header and validate its contents.

Add the AntiForgery service

Add the Antiforgery service to the service collection in Startup.ConfigureServices() after the call to AddMvc():

services.AddAntiforgery(options => {     options.HeaderName = "X-XSRF-TOKEN"; }); 

We're basically telling ASP.NET to look for the X-XSRF-TOKEN header while validating the xsrf token.

Send a cookie with the token

Now on every request from the SPA, we need to send a XSRF-TOKEN cookie with the token value. We can do that with a quick middleware:

// TODO: Refactor this to a separate middleware class app.Use(next => context => {     // TODO: Add if conditions to ensure the cookies     // are only sent to our trusted domains      // Send the token as a javascript readable token     var tokens = antiforgery.GetAndStoreTokens(context);     context.Response.Cookies.Append(         "XSRF-TOKEN",          tokens.RequestToken,          new CookieOptions() { HttpOnly = false }     );      return next(context); }); 

Validate your actions

The easiest way to validate the tokens is to add the [ValidateAntiForgeryToken] attribute. A better option is to configure MVC to apply the AutoValidateAntiforgeryToken globally for all actions with the following in Startup.ConfigureServices():

services.AddMvc(options =>      options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())); 

Read the docs on token validation.

Read More

Tuesday, October 24, 2017

Using OData in .NET Core Web API for MongoDB

2 comments

OData is now supported in .NET Core and 7.2.0 was released. But can it be used with MongoDB? I have searched, but I could not find anything that says one way or the other.

EDIT:

I've found a nuget package https://www.nuget.org/packages/microsoft.aspnetcore.odata and in ConfigureServices I've added this:

And this seems to work for me:

public void ConfigureServices(IServiceCollection services) {     ...     services.AddOData();     services.AddSingleton<IODataModelManger, ODataModelManager>(DefineEdmModel);     ... }  private ODataModelManager DefineEdmModel(IServiceProvider services) {     var modelManager = new ODataModelManager();      var builder = new ODataConventionModelBuilder();     builder.EntitySet<TestDTO>(nameof(TestDTO));     builder.EntityType<TestDTO>().HasKey(ai => ai.Id); // the call to HasKey is mandatory     modelManager.AddModel(nameof(Something), builder.GetEdmModel());      return modelManager; } 

Controller

[HttpGet("all")] public async Task<IQueryable<TestDTO>> Get() {     // plug your entities source (database or whatever)     var test = await TestService.GetTest();      var modelManager = (IODataModelManger)HttpContext.RequestServices.GetService(typeof(IODataModelManger));     var model = modelManager.GetModel(nameof(Something));     var queryContext = new ODataQueryContext(model, typeof(TestDTO), null);     var queryOptions = new ODataQueryOptions(queryContext, HttpContext.Request, Provider);      return queryOptions         .ApplyTo(test, new ODataQuerySettings         {             HandleNullPropagation = HandleNullPropagationOption.True         }, null)         .Cast<TestDTO>(); } 

Service

public async Task<IQueryable<TestDTO>> GetTest() {     return await GenericRepository.TestAll(); } 

Repositories

public async Task<IQueryable<TEntity>> TestAll() {     var res = new GetManyResult<TEntity>();     try     {         DateTime startTime = DateTime.Now;         var collection = GetCollection<TEntity>().AsQueryable();         var entities = collection.ToArray<TEntity>().AsQueryable();         return entities } 

But is this the best way to do it?

I mean, shouldn't the collection contain only the elements that meet the filters, beeing more optimised?

If yes, how do I achieve this?

1 Answers

Answers 1

I think theres only currently one connected service available in the visual studio market place for MongoDB. Link Here.

ODBC Driver for MongoDB provides high-performance and feature-rich connectivity solution for ODBC-based applications to access MongoDB databases from Windows, MacOS, Linux. Full support for standard ODBC API functions, MongoDB data types and SQL queries implemented in our driver makes interaction of your database applications with MongoDB fast, easy and extremely handy.

Looks like it would handle all of the things you'd expect it to when connecting to MongoDB.

However it's worth noting that, that is only a trail and I've been unable to find any 'open source' versions

Read More

Friday, September 29, 2017

Returning File() returns more bytes

Leave a Comment

Consider the following code:

//get bytes var query = await _storage.Get(attachment.Id, General.ContainerType.Uploads); //just for the sake of debugging var mem = new MemoryStream(query); //return the uploaded file return File(mem, MimeTypesMap.GetMimeType(attachment.FileName), attachment.FileName); 

After uploading a .jpg image of 67kb and then downloading it with this method, the returned image is 107 kb. I have checked whether the bytes are stored and retrieved correctly and they indeed are constistent with what I have uploaded. If I upload a text file and return it the content and the size is correct.

I assume File() does some magic, but I can't figure out why and what?

1 Answers

Answers 1

Its not about the File but it is something to do with the MemoryStream , for getting bytes stored in memorystream passing an entire stream is not appropriate way better to use its convenient ToArray() method. You could try with the Binarywriter

Read More