小编Dav*_*ang的帖子

.NET Core 3.1 基于角色的授权失败,出现 403 异常

我正在尝试使用 Microsoft 身份库进行角色库授权,但失败了。

  • 我可以验证用户
  • 我看到用户所属的角色与我在控制器上的角色相匹配
  • 当我去那个控制器时,我收到 403 Forbidden 错误

我不知道如何进一步调试它。

启动:

services.AddIdentity<User, UserRole>(opt => opt.User.RequireUniqueEmail = true)
    .AddRoles<UserRole>()
    .AddEntityFrameworkStores<EntityDbContext>()
    .AddDefaultTokenProviders();

var jwtSetting = _configuration
    .GetSection("JwtSettings")
    .Get<JwtSettings>();

services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(config =>
    {
        config.RequireHttpsMetadata = false;
        config.SaveToken = true;

        config.TokenValidationParameters = new TokenValidationParameters
        {
            ValidIssuer = jwtSetting.Issuer,
            ValidAudience = jwtSetting.Audience,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSetting.Key))
        };
    });
Run Code Online (Sandbox Code Playgroud)

我的控制器角色:

[Authorize(Roles = "Internal")]
[ApiController]
[Route("Api/[controller]")]
public class UserController : BasicCrudController<User>
{
     // Stuff here ...
}
Run Code Online (Sandbox Code Playgroud)

回购网址

c# .net-core asp.net-core-identity

6
推荐指数
1
解决办法
1853
查看次数

如何在 .NET core 中从基于组织的身份设置/查找用户角色

我试图找出用户在 Blazor Server 应用程序中具有哪些角色,该应用程序为使用 MS 帐户和 Azure Active Directory 的组织设置了身份验证。我想这些角色是由管理 MS 帐户的 IT 运营团队设置的,但我没有找到在哪里验证这一点。

所以我想知道:使用 Org 身份验证时在哪里设置角色如何更改它们是否有一种简单的方法来查看经过身份验证的用户具有哪些角色

我尝试使用级联参数在MS doc示例代码中查找经过身份验证的用户角色,如下所示:

@page "/"

<button @onclick="LogUsername">Log username</button>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        LogUsername();
    }

    private async Task LogUsername()
    {
        var authState = await authenticationStateTask;
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            var test = user.Claims.Where(c => c.Type.Contains("Role")); // also tried "role"
            string role = …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-identity blazor

6
推荐指数
1
解决办法
7478
查看次数

如何对将在多个步骤中创建的聚合进行建模,例如向导样式

我将以Airbnb为例。

注册爱彼迎账户后,您可以通过创建房源成为房东。要创建房源,Airbnb UI 将指导您分多个步骤完成创建新房源的过程:

在此处输入图片说明

它还会记住您走过的最远的一步,所以下次当您想继续该过程时,它会重定向到您离开的地方。


我一直在努力决定是否应该将列表作为聚合根,并将方法定义为可用步骤,还是将每个步骤视为它们自己的聚合根,以便它们很小?

列为聚合根

public sealed class Listing : AggregateRoot
{
    private List<Photo> _photos;

    public Host Host { get; private set; }
    public PropertyAddress PropertyAddress { get; private set; }
    public Geolocation Geolocation { get; private set; }
    public Pricing Pricing { get; private set; }
    public IReadonlyList Photos => _photos.AsReadOnly();
    public ListingStep LastStep { get; private set; }
    public ListingStatus Status { get; private set; }

    private Listing(Host host, PropertyAddress propertyAddress)
    {
        this.Host = host;
        this.PropertyAddress …
Run Code Online (Sandbox Code Playgroud)

c# domain-driven-design aggregateroot

6
推荐指数
1
解决办法
328
查看次数

ASP.NET Core MVC 中的匿名标识

在以前的 ASP.NET MVC 中,您可以通过在以下代码中添加 1 行来轻松打开匿名身份验证web.config

<anonymousIdentification enabled="true" />
Run Code Online (Sandbox Code Playgroud)

我们可以使用匿名身份识别,即Request.AnonymousID识别您网站上未经身份验证的用户。当您需要针对访客保存购物车中的商品时,这对于电子商务体验非常有用。

更多信息:http://www.toplinestrategies.com/blogs/net/anonymous-identification-mvc

问题:

Request.AnonymousID来自System.Web,随着 ASP.NET Core 的出现而消失。

问题:

  1. 如何在 ASP.NET Core MVC 中启用匿名身份识别?
  2. 如果 1 不可能,您将如何“识别”您网站上的访问者?

注意:我不想使用会话来存储对象。

c# anonymousidentification asp.net-core-mvc

5
推荐指数
1
解决办法
2052
查看次数

如何在 asp.net core web api 的控制器中使用模型绑定排除属性

您好,当模型到达控制器(Web API)中的操作时,我试图从模型中排除一个属性,

我尝试过[Bind(Exclude ="something")],但似乎它不属于 .net core api

model-binding asp.net-web-api asp.net-core

5
推荐指数
3
解决办法
7662
查看次数

AspNet Identity RequireClaim() - 如何使用 OR?

我有这个 Visual Studio Identity 代码

namespace BlazorBoilerplate.Shared.AuthorizationDefinitions
{
    public static class Policies
    {
        public const string IsAdmin = "IsAdmin";
        public const string IsUser = "IsUser";
        public const string IsReadOnly = "IsReadOnly";
        public const string IsMyDomain = "IsMyDomain";

        public static AuthorizationPolicy IsAdminPolicy()
        {
            return new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireClaim("IsAdministrator")
                .Build();
        }

        public static AuthorizationPolicy IsUserPolicy()
        {
            return new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireClaim("IsUser")
                .Build();
        }

        public static AuthorizationPolicy IsReadOnlyPolicy()
        {
            return new AuthorizationPolicyBuilder()
                .RequireAuthenticatedUser()
                .RequireClaim("ReadOnly", "true")
                .Build();
        }

        public static AuthorizationPolicy IsMyDomainPolicy()
        {
            return …
Run Code Online (Sandbox Code Playgroud)

c# authorization policies asp.net-identity

5
推荐指数
1
解决办法
1016
查看次数

如何通过 Razor Pages 扩展 ASP.NET Core MVC 项目?

我目前正在尝试通过 Razor 页面扩展现有的 ASP.NET Core MVC 项目(因为几个教程视频声称 MVC、API、Razor 和 Blazor 可以在同一个项目中共存 - 但没有一个显示它是如何完成的)。

我已经发现我需要通过以下方式扩展 Startup.cs

services.AddRazorPages();
Run Code Online (Sandbox Code Playgroud)

app.UseEndpoints(endpoints =>
{
    // This was here already
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    // I added this
    endpoints.MapRazorPages();
});
Run Code Online (Sandbox Code Playgroud)

我尝试简单地在Views文件夹中添加一个剃刀页面“测试” ,_Layout.cshtml通过

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Test">Test</a>
</li>
Run Code Online (Sandbox Code Playgroud)

然后HomeController通过

    public IActionResult Test()
    {
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

但是,这会导致几个问题,即未命中断点或ViewData字典null(在纯 Razor 页面项目中使用相同的代码),可能是因为它尝试将 Razor 页面视为 MVC 视图或其他东西。

我也试过添加类似的东西

<li class="nav-item">
    <a class="nav-link text-dark" asp-area="" asp-page="/Home/Test">Test</a> …
Run Code Online (Sandbox Code Playgroud)

c# asp.net razor asp.net-core-mvc asp.net-core

5
推荐指数
1
解决办法
2652
查看次数

System.AggregateException:“无法构建某些服务”在我的 ASP.net 核心中

我有一个模型:

public class Checkout
{
    public string CheckoutId { get; set; }

    public List<CheckoutItem> CheckoutItems { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我试图在尊重 POCO 的同时向对象添加方法。所以我添加了一个存储库:

    public class CheckoutRepository : ICheckoutRepository
    {
        private readonly AppDbContext _appDbContext;
        private readonly Checkout _checkout;

        public CheckoutRepository(AppDbContext appDbContext, Checkout checkout)
        {
            _appDbContext = appDbContext;
            _checkout = checkout;

        }

        public void AddItem(unitItem item, int amount)
        {
              //Removed for brevity 
        }

        public void ClearCheckout()
        {
           //Details removed for brevity
        }

        public Checkout GetCart(IServiceProvider serviceProvider)
        {   
          //Details removed for brevity
        } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core-mvc asp.net-core

5
推荐指数
1
解决办法
1万
查看次数

MVC视图层MongoDB连接信息的依赖注入

我试图按照本教程熟悉使用 .Net Core 的 MVC 和数据层来处理 MongoDB 信息的分层解决方案中的依赖项注入:https://code-maze.com/getting-started-aspnetcore-mongodb/

我的 .sln 设置如下:

项目A----MVC层

项目B ---- MongoDB层

我想要做的是使用我在视图的DB层中定义的函数来显示文档的信息。我遇到的问题是弄清楚如何调用 Index .cshtml 中的函数。

接下来,我首先创建一个接口来从服务中提取连接信息。由于A依赖于B,所以我在B中这样写:

namespace DataLayer
{
    public class MyDBSettings : IDotNetStudyDBSettings
    {
        public string FileHistoryCollectioName { get; set; }
        public string FileResultsCollectionName { get; set; }
        public string ConnectionString { get; set; }

        public string DatabaseName { get; set; }



    }


    public interface IDotNetStudyDBSettings
    {
        string FileHistoryCollectioName { get; set; }
        string FileResultsCollectionName { get; set; }
        string ConnectionString { get; set; …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection mongodb asp.net-core-mvc .net-core

5
推荐指数
1
解决办法
5630
查看次数

缺少程序集引用 - 但我相信该包已正确引用

当我注册以下using声明时:

using Microsoft.AspNetCore.Identity.UI;
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

命名空间“Microsoft.AspNetCore.Identity”中不存在“UI”类型或命名空间名称(缺少程序集引用?)

在我看来,一切都很顺利。我将 a 添加<PackageReference>NuGet 包Microsoft.AspNetCore.Identity.UI。但错误仍然存​​在。

我该如何解决这个问题?

我的.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.4" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SQLite" Version="3.1.3" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.3" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.1.1" />
  </ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

和我的AssemblyInfo.cs

using System;
using System.Reflection;

[assembly: Microsoft.AspNetCore.Identity.UI.UIFrameworkAttribute("Bootstrap4")]
[assembly: System.Reflection.AssemblyCompanyAttribute("ESporcum")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core asp.net-core-identity

4
推荐指数
1
解决办法
4745
查看次数