Comments (8)
Did you registered the user by the application?
Did you validate the data in the Claims table?
from equinoxproject.
Yes. There're two records in user claims table.
from equinoxproject.
I updated to the ASP.NET 2.0 version and tested the authorization rules. It's working fine.
from equinoxproject.
Hello Eduardo,
Did you registered the user by the application? YES
Did you validate the data in the Claims table? YES
In claim table I have:
Id | ClaimType | ClaimValue | UserId | |
---|---|---|---|---|
9 | Parks | Write | 925dbffb-731d-40e8-b4e4-d4eb4986e07c | |
10 | Parks | Read | 925dbffb-731d-40e8-b4e4-d4eb4986e07c | |
11 | Parks | Remove | 925dbffb-731d-40e8-b4e4-d4eb4986e07c |
In Users table:
Id | AccessFailedCount | ConcurrencyStamp | EmailConfirmed | LockoutEnabled | LockoutEnd | NormalizedEmail | NormalizedUserName | PasswordHash | PhoneNumber | PhoneNumberConfirmed | SecurityStamp | TwoFactorEnabled | UserName | ||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
925dbffb-731d-40e8-b4e4-d4eb4986e07c | 0 | 6657e43b-4ad9-408f-978a-c486339d5404 | [email protected] | False | True | (NULL) | [email protected] | [email protected] | AQAAAAEAACcQAAAAEOnnYPjyqBo9hMqz77agLaMS15b7zh8LQduamBzCqdsy1gFTGSEnwBAxDWiRb6xiHg== | (NULL) | False | 41b74c38-6fa1-4381-a386-ebb75df55b56 | False | [email protected] |
Controller Method:
[HttpGet]
[Authorize(Policy = "CanReadParkData")]
[Route("park-management/list-all")]
public IActionResult Index()
{
return View(_parkAppService.GetAll());
}
Startup.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o => {
o.LoginPath = new PathString("/login");
o.AccessDeniedPath = new PathString("/home/access-denied");
})
.AddFacebook(o =>
{
o.AppId = Configuration["Authentication:Facebook:AppId"];
o.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
}); ;
services.AddMvc();
services.AddAutoMapper();
services.AddAuthorization(options =>
{
options.AddPolicy("CanWriteParkData", policy => policy.Requirements.Add(new ClaimRequirement("Parks","Write")));
options.AddPolicy("CanRemoveParkData", policy => policy.Requirements.Add(new ClaimRequirement("Parks", "Remove")));
options.AddPolicy("CanReadParkData", policy => policy.Requirements.Add(new ClaimRequirement("Parks", "Read")));
});
// Configure Identity
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
// User settings
options.User.RequireUniqueEmail = true;
});
// Adding MediatR for Domain Events and Notifications
services.AddMediatR(typeof(Startup));
// .NET Native DI Abstraction
RegisterServices(services);
}
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IHttpContextAccessor accessor)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
//app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=welcome}/{id?}");
});
}
private static void RegisterServices(IServiceCollection services)
{
// Adding dependencies from another layers (isolated from Presentation)
NativeInjectorBootStrapper.RegisterServices(services);
}
}
from equinoxproject.
@digounet What you have at AspNetUserClaims
table?
from equinoxproject.
Try putting all together like:
Write, Remove, Create ......
from equinoxproject.
@EduardoPires @thiagolunardi Solved:
In ClaimsRequirementHandler i've changed the method HandleRequirementAsync to:
```
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
ClaimRequirement requirement)
{
var claim = context.User.Claims.FirstOrDefault(c => c.Type == requirement.ClaimName && c.Value == requirement.ClaimValue);
if (claim != null)
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
The error occur because the original implementation gets only the first result of the claims table:
`var claim = context.User.Claims.FirstOrDefault(c => c.Type == requirement.ClaimName);`
from equinoxproject.
That's Right! the original implementation get only the first row.
from equinoxproject.
Related Issues (20)
- 为什么只有事件保存,没有事件查询,希望通过DynamicApiControllerInfo根据Serivce 自动生成WebAPI HOT 1
- hello,where is identity context? How to use
- Exempt de Azure Function com DI HOT 2
- CRUD para um Aggregate com Child Enity HOT 2
- Some services are not able to be constructed (Error while validating the service descriptor) HOT 2
- Essa arquitetura CQRS + ES ainda é considerada válida? HOT 3
- Need migration commands to start with the projects HOT 1
- Api generating an invalid JTW signature HOT 1
- Customizar IdentityUser HOT 1
- Ajuda para teste Teste de unidade para o CommandHandler e assert do evento publicado HOT 1
- implement business rules involving multiple entities HOT 1
- When updating Identity Migration in the Equinox.UI.Web layer an error is appearing that the object of type ApplicationDbContext cannot be created HOT 8
- Relate in EquinoxContext AspNetUsers with Employee HOT 1
- Why is ApplicationDbContext.cs inside Equinox.UI.Web project? this is nonsense HOT 1
- customer history api non consistent with the name between API and Web project
- EquinoxProject is not sample of EventSourcing, but sample of audith log
- Doubt in migrations HOT 1
- update-database HOT 2
- Project still active? HOT 2
- Update DataBase HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from equinoxproject.