User.IsInRole("admin") No Working! -> Data entered manually. Missing anything? - c#

Manual database inserts: user in AspNetUser. Role in AspNetRoles. I used both ids and added them in AspNetUserRoles.
Program.cs:
builder.Services.AddIdentity<AppUser, IdentityRole>(options
=> options.SignIn.RequireConfirmedAccount = true)
.AddUserManager<UserManager>()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders()
.AddDefaultUI();
I am using the code to verify the role: User.IsInRole("admin")
--> But I am still getting false there.
-> Can anyone share what might cause this problem?
-> Do I need to add anything in middleware (program.cs)?
-> Do I need to add anything in any other database? (AspNetClaims?)
-> Or that is happening because of - I inserted the role manually in the database? (Not run the program and register from app)
Database used: MySql 8.0
Project: ASP.NET MVC 6.0
UPDATE:
Debug: When I hover on User.IsInRole("Admin") and narrow down to: user->Claims-> I find 5 items:
../claims/nameidentifier: ..
../claims/name: ..
../claims/emailadrress: ..
AspNet.Identity.SecurityStamp
amr:pwd
-> I guess something related to role should be there? How can I add it there?

Related

Piranha CMS new menu for the manager

I have successfully created a new menu item to the manager. The downside is that those who are not logged in can view the menu item and page. So far I have this C# code within Startup.cs and the method Configure():
Menu.Items["Competitions"].Items.Add(new MenuItem
{
InternalId = "CompetitionData",
Name = "Competition data",
Route = "~/manager/Competitions/CompetitionData",
Css = "fas fa-file-excel"
});
I know that I need to add the Policy property to the above code, but I don't know what value I should put in there. I have tried various values but either the code falls over, or it runs and the "public" can view the URL.
First of all I can't find any documentation about the Policy property, and secondly, I don't understand the link between roles, claims and policies. I would be grateful if anyone could point me in the right direction.
Thank you very much.
Policies are a standard feature and is basically a named collection of one or more claims. You need to add the policies in your startup code or else the code, like you say, will fail when the code references an unknown policy.
Here’s an example of where the Identity module for Piranha adds it’s custom policies that is used in the manager.
https://github.com/PiranhaCMS/piranha.core/blob/master/identity/Piranha.AspNetCore.Identity/IdentityModuleExtensions.cs#L56
Best regards
Håkan

.net core 3.1 call to User Secrets for SendGrid keys returns null values

I have set up a project following https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-3.1&tabs=visual-studio
From Startup.cs:
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
_secretOne = Configuration["SecretStuff:SecretOne"];
the _secretOne variable was added to prove that the correct secrets.json file is being accessed. It has both a SecretStuff block and a AuthMessageSenderOptions block.
In EmailSender.cs
public EmailSender(IOptions<AuthMessageSenderOptions> optionsAccessor)
{
Options = optionsAccessor.Value;
}
A breakpoint after Options = shows the keys with null values.
Eventually I gave up and hard coded the Options.SendGridKey and Options.SendGridUser and with this change the project works as it should.
This is my first use of User-Secrets so when it did not work I set up a console app that references the same secrets.json file and it sends emails.
I found a possible answer in: https://www.twilio.com/blog/2018/05/user-secrets-in-a-net-core-web-app.html
I changed Startup.cs to:
services.Configure<AuthMessageSenderOptions>(Configuration.GetSection("AuthMessageSenderOptions"));
and now the values are as they should be. I sure wasted a lot of time looking in the wrong places for an answer.

Problem generating Swagger definitions using custom naming strategy

I have an OData Web API and I'm using Swashbuckle and Swagger to generate and display Web API documentation. This was working and producing nice definition names, like so:
User
Role
Permission
ODataResponse[List[Permission]]
CoordinateSystem
Etc...
I ran into an issue with "Conflicting schemaIds" after adding some new objects and controllers and started getting this error:
System.InvalidOperationException: 'Conflicting schemaIds: Duplicate schemaIds detected for types Microsoft.Spatial.CoordinateSystem and MyProject.CoordinateSystem. See the config setting - "UseFullTypeNameInSchemaIds" for a potential workaround'
As the error states, I added the following line in SwaggerConfig.cs
c.UseFullTypeNameInSchemaIds();
This fixed the error but caused some issues with my definition names. Now they show up like this:
MyProject.User
MyProject.Role
MyProject.Permission
Swashbuckle.OData.ODataResponse[System.Collections.Generic.List[MyProject.Permission]]
MyProject.CoordinateSystem
Microsoft.Spatial.CoordinateSystem
The third last one is problematic now as it is too long for the app that reads this information.
Next, I tried using the custom strategy example provided in SwaggerConfig.cs to rename one of the conflicting definition names:
c.SchemaId(t => t.FullName.Contains("Microsoft.Spatial.CoordinateSystem")
? t.FullName : t.Name);
This works for the conflicting definitions as it uses the full name for "Microsoft.Spatial.CoordinateSystem" and I get this now:
User
Role
Permission
ODataResponse`1
CoordinateSystem
Microsoft.Spatial.CoordinateSystem
The problem now is "ODataResponse`1". I'm expecting "ODataResponse[List[Permission]]" but it is displaying the name of the Swashbuckle.OData definition only. There are other options - I tried t.FullName, t.Name, t.AssemblyQualifiedName, t.Namespace but none produce the desired results.
I did come up with a solution that works using the custom naming strategy but it looks horrible and is super hacky:
c.SchemaId(t => t.FullName.Contains("System.Collections.Generic.List") ?
"ODataResponse[List[" +
t.FullName.Substring(t.FullName.IndexOf("MyProject.") + 10, (t.FullName.IndexOf(",") - 10 - t.FullName.IndexOf("MyProject.")))
+ "]]"
: (t.FullName.Contains("Microsoft.Spatial.CoordinateSystem") ? t.FullName : t.Name));
Does this seem to be a bug within Swagger/Swashbuckle or am I doing something wrong with the c.SchemaId code?

Is there a way to use the 'AllowAnyOrigin' property on a CorsPolicy within .NET Core?

I'm currently working on integrated Cors within a .Net Core app. I have previously dealt with Cors within the full .NET Framework (4.6.1) which had the ability to set the AllowAnyOrigin property within a given CorsPolicy.
Like mentioned before, I have written a .NET Core WebApi, which I am trying to implement Cors into. I have it reading from an AppSetting stored in my appSettings.json, from which it can be either three things:
If the appsetting is set to an asterisk, then I would like to see the AllowAnyOrigin property like I have done in the full .NET framework. (This is where my problem lies.)
If the appsetting is set to a comma seperated string, such as https://example.com, https://test.com, then this is applied onto the policy as needed.
If the appsetting has been commented out or left as empty, then I am reading a list of rows from Azure Table Storage to supply a list of given origins.
Below is an example of the full .NET framework that I have dealt with before.
var origins = ConfigurationManager.AppSettings[KeyCorsAllowOrigin];
switch (origins)
{
case null:
_corsPolicy.Origins.Clear();
foreach (var item in new StorageConfigurationManager().GetRowKeys())
{
_corsPolicy.Origins.Add("https://" + item);
}
break;
case "*":
_corsPolicy.AllowAnyOrigin = true;
break;
default:
_corsPolicy.AllowAnyOrigin = false;
if (!string.IsNullOrWhiteSpace(origins)) AddCommaSeparatedValuesToCollection(origins, _corsPolicy.Origins);
break;
}
I thought that I could replicate this functionality within .NET Core and the Microsoft.AspNetCore.Cors.Infrastructure package, but it seems that Microsoft has restricted access to setting the property, and can only be read from.
Does anyone know of any way to set this?
I know you can build the CorsPolicy within the pipeline, which then uses the .AllowAnyOrigin(), but I am currently using custom Cors middleware to help with my custom policy.
There is a great article called Enabling CORS in ASP.NET Core I'll sum the interesting part for you:
to only allow GET methods on your resource, you can use the WithMethods method when you define the CORS policy:
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder => builder.WithOrigins("http://localhost:55294")
.WithMethods("GET"));
});
If you need to allow any origin to access the resource, you will use AllowAnyOrigin instead of WithOrigins:
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin",
builder => builder.AllowAnyOrigin());
});
Just as an answer to all this, and so that perhaps someone can be helped by this question. I looked at the source code for the AllowAnyOrigin method within the CorsPolicyBuilder class and saw how this was handled. I nearly had the solution, just forgot to clear the Origins list beforehand.
_policy.Origins.Clear();
_policy.Origins.Add(CorsConstants.AnyOrigin);

signalR change default site in startup

I have an application where i have 2 instances of it running on the same IIS server.
/Site1
/Site2
same source code in both, just different settings. I have signalR code on both sites, but i would like Site2 to use the signalR server from Site1.
I have this working so that if changes are made on Site1, Site2 knows to refresh, and that works fine. THE PROBLEM is that if server changes (not javascript) are made on Site2, Site1 doesn't get them. Below is my code:
Startup.cs
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
#if DEBUG
EnableDetailedErrors = true
#endif
};
map.RunSignalR(hubConfiguration);
});
javascript code:
$.connection.hub.url = "http://servername/Site1/signalr";
...$.connection.start etc
All of that seems to work fine, but what i can't find anywhere is how to push settings in the C# code from Site2 to Site1.
random c# code:
var hub = GlobalHost.ConnectionManager.GetHubContext<myHub>();
this globalhost.connectionmanager.gethubcontext is always pointing to itself. How can i get Site2 to point to Site1 in the last section? I've tried looking into editing Startup.cs to use MapSignalR(..path,...), but the path doesn't take absolute URLs, it has to start with '/', so it won't go up a level.
Any ideas or am i missing something basic?
Apparently what i'm looking for is a backplane. https://learn.microsoft.com/en-us/aspnet/signalr/overview/performance/scaleout-in-signalr . super easy to set up, and fixed my problem immediately (without any of the javascript changes above needed).

Categories

Resources