Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

Reject a jwt token if the user is disabled in the database

$
0
0

I use jwt token in my asp.net core app and I have two issues. First, I wan to check each time the token is validated and see if the user is still active in database. I know there is OnMessageReceived event in JwtBearerEvents, but I do not know if I have to do the token validation manually or not and then extract the user id from it and validate it by calling the database. 

At the moment when I generate jwt token, I add user id to claims and I know that I can extract it as below : 

 var token = httpRequest.Headers["Authorization"].FirstOrDefault().Split(' ')[1];
            var jwtToken = handler.ReadToken(token) as JwtSecurityToken;

            SecurityToken validatedToken;
            var principal = handler.ValidateToken(token, jwtTokenValidator.GetValidationParameters(), out validatedToken);

            if (validatedToken.ValidTo >= DateTime.Now)
            {
                if (principal.Claims.Any(c => c.Type == "id"))
                {
                    return Guid.Parse(principal.Claims.First(c => c.Type == "id").Value.ToString());
                }
            }

By the way, I do not know how can I use "OnMessageReceived " to check the user status in the database each time the token is being validated. 


Replace old text for PartialView - View only when the word appears.

$
0
0

It is so that if I write something specific in my text on the page then I should have shown a form on the page when writing the simple word that I want it to be overwritten with.

The problem is right now that I can in no way make my PartialView appear.

I've looked at these here:
https://stackoverflow.com/a/19208941

It causes problems when trying to just "run" as it is now and I get this error.

Microsoft.AspNetCore.Mvc.PartialViewResult

Code her:

return text.Replace("{{text}}", PartialView("ViewHelper/Email/EmailView").ToString());

i have C# 7.3 and .net core 2.1

</div> </div> </div> </div> </div>

User Authentication using multiple identities not just single default IdentityUser

$
0
0

Hi,

I am currently working on a DogCarePlatform that has both Owners as users and Dogsitters as users. I've reached a point where I need both of those entities to be seperate Identities and act like AspNetCoreUsers. I don't know how to create a second type of Identity. This is my code up till now.

Dogsitter class:

public class Dogsitter : ApplicationUser
    {
        public Dogsitter()
        {
            this.Id = Guid.NewGuid().ToString();
            this.Appointments = new HashSet<Appointment>();
            this.Comments = new HashSet<Comment>();
        }

        public string Id { get; set; }

        public string Name { get; set; }

        public int Age { get; set; }

        public Gender Gender { get; set; }

        public DateTime DateOfBirth { get; set; }

        public string ImageUrl { get; set; }

        public string Description { get; set; }

        public decimal WageRate { get; set; }

        public string Address { get; set; }

        public decimal Rating { get; set; }

        public ICollection<Comment> Comments { get; set; }

        public ICollection<Appointment> Appointments { get; set; }
    }

Owner class:

 public class Owner : ApplicationUser
    {
        public Owner()
        {
            this.Id = Guid.NewGuid().ToString();
            this.Comments = new HashSet<Comment>();
            this.Dogs = new HashSet<Dog>();
            this.Appointments = new HashSet<Appointment>();
        }

        public string Id { get; set; }

        public string Name { get; set; }

        public string ImageUrl { get; set; }

        public decimal Rating { get; set; }

        public string Address { get; set; }

        public ICollection<Comment> Comments { get; set; }

        public ICollection<Dog> Dogs { get; set; }

        public ICollection<Appointment> Appointments { get; set; }
    }

Application user class

public class ApplicationUser : IdentityUser, IAuditInfo, IDeletableEntity
    {
        public ApplicationUser()
        {
            // Application user
            this.Id = Guid.NewGuid().ToString();
            this.Roles = new HashSet<IdentityUserRole<string>>();
            this.Claims = new HashSet<IdentityUserClaim<string>>();
            this.Logins = new HashSet<IdentityUserLogin<string>>();
        }

        // Audit info
        public DateTime CreatedOn { get; set; }

        public DateTime? ModifiedOn { get; set; }

        // Deletable entity
        public bool IsDeleted { get; set; }

        public DateTime? DeletedOn { get; set; }

        public virtual ICollection<IdentityUserRole<string>> Roles { get; set; }

        public virtual ICollection<IdentityUserClaim<string>> Claims { get; set; }

        public virtual ICollection<IdentityUserLogin<string>> Logins { get; set; }
    }

And this is the appointment class that needs to do the relations properly between Dogsitter and Owner:

public class Appointment : BaseDeletableModel<string>
    {
        public bool IsHappening { get; set; }

        public int Timer { get; set; }

        public decimal TaxSoFar { get; set; }

        public DateTime Date { get; set; }

        public DateTime StartTime { get; set; }

        public DateTime EndTime { get; set; }

        public string OwnerId { get; set; }

        public virtual Owner Owner { get; set; }

        public string DogsitterId { get; set; }

        public virtual Dogsitter Dogsitter { get; set; }
    }

After all the migrations and updates have been applied I am left with AspNetCoreUsers table that has all of the Dogsitter's and Owner's properties in one place. There are no Dogsitters or Owners tables in the end.

This is the ApplicationDbContext.cs: 

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string>
    {
        private static readonly MethodInfo SetIsDeletedQueryFilterMethod =
            typeof(ApplicationDbContext).GetMethod(
                nameof(SetIsDeletedQueryFilter),
                BindingFlags.NonPublic | BindingFlags.Static);

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        public DbSet<Dogsitter> Dogsitters { get; set; }

        public DbSet<Owner> Owners { get; set; }

        public DbSet<Comment> Comments { get; set; }

        public DbSet<Dog> Dogs { get; set; }

        public DbSet<Appointment> Appointments { get; set; }

        public DbSet<Setting> Settings { get; set; }

        public override int SaveChanges() => this.SaveChanges(true);

        public override int SaveChanges(bool acceptAllChangesOnSuccess)
        {
            this.ApplyAuditInfoRules();
            return base.SaveChanges(acceptAllChangesOnSuccess);
        }

        public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) =>
            this.SaveChangesAsync(true, cancellationToken);

        public override Task<int> SaveChangesAsync(
            bool acceptAllChangesOnSuccess,
            CancellationToken cancellationToken = default)
        {
            this.ApplyAuditInfoRules();
            return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            // Needed for Identity models configuration
            base.OnModelCreating(builder);

            builder.Entity<Appointment>()
                .HasOne(p => p.Owner)
                .WithMany(t => t.Appointments)
                .HasForeignKey(m => m.OwnerId)
                .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<Appointment>()
                .HasOne(p => p.Dogsitter)
                .WithMany(t => t.Appointments)
                .HasForeignKey(m => m.DogsitterId)
                .OnDelete(DeleteBehavior.Restrict);

            ConfigureUserIdentityRelations(builder);

            EntityIndexesConfiguration.Configure(builder);

            var entityTypes = builder.Model.GetEntityTypes().ToList();

            // Set global query filter for not deleted entities only
            var deletableEntityTypes = entityTypes
                .Where(et => et.ClrType != null && typeof(IDeletableEntity).IsAssignableFrom(et.ClrType) && et.BaseType == null);
            foreach (var deletableEntityType in deletableEntityTypes)
            {
                var method = SetIsDeletedQueryFilterMethod.MakeGenericMethod(deletableEntityType.ClrType);
                method.Invoke(null, new object[] { builder });
            }

            // Disable cascade delete
            var foreignKeys = entityTypes
                .SelectMany(e => e.GetForeignKeys().Where(f => f.DeleteBehavior == DeleteBehavior.Cascade));
            foreach (var foreignKey in foreignKeys)
            {
                foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
            }
        }

        private static void ConfigureUserIdentityRelations(ModelBuilder builder)
        {
            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Claims)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Logins)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Restrict);

            builder.Entity<ApplicationUser>()
                .HasMany(e => e.Roles)
                .WithOne()
                .HasForeignKey(e => e.UserId)
                .IsRequired()
                .OnDelete(DeleteBehavior.Restrict);
        }

        private static void SetIsDeletedQueryFilter<T>(ModelBuilder builder)
            where T : class, IDeletableEntity
        {
            builder.Entity<T>().HasQueryFilter(e => !e.IsDeleted);
        }

        private void ApplyAuditInfoRules()
        {
            var changedEntries = this.ChangeTracker
                .Entries()
                .Where(e =>
                    e.Entity is IAuditInfo &&
                    (e.State == EntityState.Added || e.State == EntityState.Modified));

            foreach (var entry in changedEntries)
            {
                var entity = (IAuditInfo)entry.Entity;
                if (entry.State == EntityState.Added && entity.CreatedOn == default)
                {
                    entity.CreatedOn = DateTime.UtcNow;
                }
                else
                {
                    entity.ModifiedOn = DateTime.UtcNow;
                }
            }
        }
}

I would really like some input here. Thanks in advance.

IndexOutOfRangeException: Worksheet position out of range. using EpPlus

$
0
0

[HttpPost]
public async Task <IActionResult> Import(IFormFile file)
{
if(file ==null||file.Length==0)
return Content("File Not Selected");
string fileExtension=Path.GetExtension(file.FileName);
if(fileExtension==".xls"||fileExtension==".xlsx")
{
var rootFolder=@"Upload";
var fileName=file.FileName;
var filePath=Path.Combine(rootFolder,fileName);
// var filePath = @"Upload/Semester.xlsx";
var fileLocation=new FileInfo(filePath);
using(var fileStream=new FileStream(filePath,FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
if(file.Length<=0)
return BadRequest();
using(ExcelPackage package=new ExcelPackage(fileLocation))
{
ExcelWorksheet workSheet=package.Workbook.Worksheets[0];

MQTT Authentification in Asp .Net Core 3.1

$
0
0

Hello can anyone advise how to implement Authentification(username and password FROM DB level) in MQTT platform, currently have few ideas in mind:

1. Authenticate on every message received from client, problem is database would get huge load just for checking if many users are provide valid login data.

2. Implement other authentication solution(JWT?), then how to implement in current solution(link to github)

There are two projects one Asp .Net core MQTT "server" and other .Net Core Console App "client"

Github link to plain MQTT implementation(Mosquitto config also included if anyone needs it)

Github

Thanks for help.

How can I set the language of Localizer by code in blazor server-side?

$
0
0

I need to embed a Blazor server-side component to an existing asp.net core project.

I followed the tutorial of this https://medium.com/@geobourno/bringing-blazor-in-an-existing-net-core-mvc-project-d605d9f9ebe8 by creating a brand new blazer server-side project in the same solution.

All works well.

Now I added the Localizer to the blazor server-side project and want to set the language of its Localizer the same as the asp.net core project(the asp.net core project is choosing the language by URL just ashttps://www.microsoft.com/en-us/).

Meanwhile, the blazor only set its language the same as the browser while running.

I think I should set a parameter(which to record the language type) of blazor component in asp.net core first. After blazor runs, it gets the parameter and set the language the same as it.

I don't know whether my idea is right but I just want to set the language of its Localizer the same as the asp.net core project dynamically.

PS:

Someone tells me to achieve it like this in OnAfterRenderAsync of blazor:

CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("zh-hant");
CultureInfo.CurrentCulture = new CultureInfo("zh-hant");
CultureInfo.CurrentUICulture = new CultureInfo("zh-hant");

Well, it doesn't work any.

How can I solve this? Thank you.

User Roles and Authentication.

$
0
0

Currently spending my time at home building an Application in MVC ASP.Net Core for a college assignment. I've managed to get both a login and registration form working and I'm now looking at User Roles and Authentication. Just looking for some guidance on the best way of doing this.

Currently I have a 'Roles' field entered into my DB with either 'Admin' and 'User', I then made an 'Admin' and 'Users' Controller linking them to different pages:

[Authorize(Roles="Admin")]
    public class AdminController : Controller
    {
        private readonly DefaultContext _context;
        public AdminController(DefaultContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            return View();
        }
    }

I'm not quite sure on how I go about checking the [Authorize(Roles="Admin")]  to the 'Roles' column within my database? 

How to assign a list to object member?

$
0
0

List<DateTime> lstdt is loaded with items. I want to assign

Student.ClassAttendance=lstdt; 

Or Can we make use of code like-

 List<DateTime>(Enumerable.Range(1, 5).Select(x => DateTime.Now));


Getting a Null Result When i try to create user, using the asp.net core default user

$
0
0

So I am using asp.net core user (Authentication and Authorization system). I have seeded my tables newly default tables need for user and roles management have been created but they are all empty.

So I am trying to create a new user.

 var user = new ApplicationUser { Firstname = model.Firstname,Lastname = model.Lastname, UserName = model.Email,  Email = model.Email,  };
                var result = await _userManager.CreateAsync(user, model.Password);

But when I send values to my action method  var result =  ends up been equals to null. This is causing a null pointer exception. What am I doing wrong. I felt user should be created on the spot. Do I need to seed roles. I dont konw what do here.

Thanks alot.

Best Regards.

Need to change model/database table in .Net Blazor-Server-Side app

$
0
0

I am building a CRUD app from a Blazor serverside project that also has EntityFramework Power Tools integrated. The initial framework I am using is from an example that is already configured with authentication identity objects. The example has the stock WeatherForecast aboard, and now that I have tested everything with the registration, logins, CRUD functionalities, I want to use one of my tables in my remote database to integrate my own thing. I am confused as in MVC , you can go to the .edmx and do an "update model from database" to make changes to your modeling. 
In the EFPT.config.json file, it shows this entry for "Tables":
"Tables": [
{
"HasPrimaryKey": true,
"Name": "[dbo].[WeatherForecast]"

}
],

....

..where as the myprojectnameContext.cs class references "some' of the field names here:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasAnnotation("ProductVersion", "2.2.0-rtm-35687");

modelBuilder.Entity<WeatherForecast>(entity =>
{
entity.Property(e => e.Date).HasColumnType("datetime");

entity.Property(e => e.Summary).HasMaxLength(50);

entity.Property(e => e.UserName).HasMaxLength(50);
});

OnModelCreatingPartial(modelBuilder);
}


.... , but it's not all the fields for the WeatherForecast table, as the TemperatureC and TemperatureF fields are not present in this method, tho they are in myprojectname/WeatherForecast.cs

namespace EndToEndDB.Data.EndToEnd
{
public partial class WeatherForecast
{
public int Id { get; set; }
public DateTime? Date { get; set; }
public int? TemperatureC { get; set; }
public int? TemperatureF { get; set; }
public string Summary { get; set; }
public string UserName { get; set; }
}
}

...
..so while the authentication-identity objects are working and the CRUD functionality is too, i'd like to merely change the table to my "Products" table and the model, but very confused after reading many online tutorials and articles.

Thanks in advance
Ned

ASP.NET 3.0 : ArgumentException: Options.ClientId must be provided (Parameter 'ClientId')

$
0
0

I have ASP.NET 3.0 Application, Below is my code When I hit breakpoint I can see my client Id is not null still it results into error

var Test = new OpenIdConnectOptions();
Test.Authority = "XXXXXX"
Test.ClientId = "YYYYYY";
Test.ClientSecret = "ZZZZZZ";

ArgumentException: Options.ClientId must be provided (Parameter 'ClientId')

Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectOptions.Validate()

Microsoft.AspNetCore.Authentication.RemoteAuthenticationOptions.Validate(string scheme)

Microsoft.AspNetCore.Authentication.AuthenticationBuilder+<>c__DisplayClass4_0<TOptions, THandler>.<AddSchemeHelper>b__1(TOptions o)

Microsoft.Extensions.Options.ValidateOptions<TOptions>.Validate(string name, TOptions options)

Microsoft.Extensions.Options.OptionsFactory<TOptions>.Create(string name)

Microsoft.Extensions.Options.OptionsMonitor<TOptions>+<>c__DisplayClass11_0.<Get>b__0()

System.Lazy<T>.ViaFactory(LazyThreadSafetyMode mode)

System.Lazy<T>.CreateValue()

System.Lazy<T>.get_Value()

Microsoft.Extensions.Options.OptionsCache<TOptions>.GetOrAdd(string name, Func<TOptions> createOptions)

Microsoft.Extensions.Options.OptionsMonitor<TOptions>.Get(string name)

Microsoft.AspNetCore.Authentication.AuthenticationHandler<TOptions>.InitializeAsync(AuthenticationScheme scheme, HttpContext context)

Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, string authenticationScheme)

IdentityServer4.Hosting.FederatedSignOut.FederatedSignoutAuthenticationHandlerProvider.GetHandlerAsync(HttpContext context, string authenticationScheme)

Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)

IdentityServer4.Hosting.BaseUrlMiddleware.Invoke(HttpContext context)

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Asp.Net Core ECDH

$
0
0

Hi,

I would like to know if there is a example where ASP.NET core exchange ECDH key with a dot.net Core console app ?  Thank you

a quick reflections question

$
0
0

i have this

public class ClassA
{
     public IList<ClassB> PropertyB { get; set; } = new List<ClassB>();
}

public class ClassB
{

}

var a = new ClassA().PropertyB.GetType();
var p = new ClassA().GetType().GetProperty("PropertyB").GetType();

Assert.IsTrue(a.IsGenericType);//This passes
Assert.IsTrue(p.IsGenericType);//This fails 

and someone explain why?

FileStream.CopyToAsync copies the file empty with size of 0

$
0
0

Hi

I'm trying to upload files to some destination folder in wwwroot source folder.

Now when I browse some file and save a new record in the view, the file is copied but empty with 0 size!

I've tried to put these bold in the method:

                using (var fileStream = new FileStream(newfilepath, FileMode.Create))
{
fileStream.Position = 0;
fileStream.Flush();
await fileStream.CopyToAsync(fileStream);
}

but this doesn't solve the problem. How to solve please?

linq with groupby giving syntax error

$
0
0

var stat = (from s in _context.Subjects
join a in _context.Attendances on s.Code equals a.Code
where ((((a.Atten.Count(x => x == '1') * 100) / a.Atten.Length) > scutoff) && s.SemId.Contains(filtsemid))
into sstat select new Stat {
Code = sstat.Code, Name = sstat.Name, SemId = sstat.SemId, Shortage = sstat.Count() })
.GroupBy(s => new { Code = s.Code, Name = s.Name, SemId = s.SemId })
.AsNoTracking();


Can i get a list of all properties but only in the direvide class?

$
0
0

Hi

I have

public class MyClassA
{
   public string ThisProperty {get;set;}

   public IList<string> GetAllPropertiesFromDerivedClass()
  {
      //needs to return One,Two and Three
      //This will be different if the derived cass is different
  }

}

public class MyClassB : MyClassA
{
   public string One {get;set;}
   public string Two {get;set;}
   public string Three {get;set;}
}

I know i could create an abstract method or virtual method and override it to hard code it (which is what i am doing at the moment), but can i do it dynamically

Any thoughts would be appriciated

Ho to migrate an existing asp.net dynamic data website/project to mvc core 3

$
0
0

It is possible to migrate an existing asp.net dynamic data website/project to mvc core 3 under vs2019?

The old dynamic data app (vs2010 EF4 ) is working just fine but it needs adjustments and we have decided trying to preserve existing programming and customization and just incorporate new features using newest language (MVC Core or/and Razor)

ASP.NET 3.1 : Dynamic Updating OpenID Connect Options

$
0
0

I am having ASP.NEt 3.1 Application adn I am trying to update my OpenIDConnection options Below is the code I am trying to use I am getting error as Client ID Parameter must be provided

public class Startup
{
    private readonly IConfiguration _appConfiguration;
    private IApplicationBuilder _appBuilder;
    public Startup(IConfiguration configuration)
    {
      _appConfiguration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
      services.AddAuthentication()
      .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, "Scheme1", options =>
      {
        //Wan to Set Client Id, Authority and Client Secret Dynamically
      });
      services.AddSingleton<OpenIdUpdater>();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
    {
      _appBuilder = app;
      app.UseAuthentication();
      app.UseStaticFiles();
      app.UseRouting();
      app.UseEndpoints(builder => builder.MapControllers());
    }
}

  public class OpenIdUpdater
  {
    private readonly IOptionsMonitor<OpenIdConnectOptions> _openIdConnectOptionsMonitor;
    public OpenIdUpdater(IOptionsMonitor<OpenIdConnectOptions> openIdConnectOptionsMonitor)
    {
      _openIdConnectOptionsMonitor = openIdConnectOptionsMonitor;
	  var opt = _openIdConnectOptionsMonitor.CurrentValue;
        opt.CLientID = "....";
        );
    }
  }

Here the problem is I am getting values of client Id after Configure Services. In Configure services values are null and I want to update them later once I get the values.

Is Blazor life for production

$
0
0

Been seeing alot of questions on Blazor lately. Is it life for production. Can blazor compete with React and Angular when it comes to speed in the Virtual dom.

Please are there sample website built on Blazor out here. Cos blazor is looking like Razor to me.

What the comparative adv of using blazor to react and angular.

I want to know if it is worth learning. Too many tech out there. no time to waste at all.

Thanks

Blazor Client Side - how intercept User Activity

$
0
0

Hi,

I want to check if a logged-In user is doing some activity.

This in client side without check and consider the http requests to the server.

Some tips ?

Thanks in advance

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>