我从ASP.NET Core 1.1升级到2.0,现在有401个未经授权的响应被更改为302重定向响应.这在以前是我在1.1中的一个问题,并通过以下代码进行了缓解:
services.AddIdentity<User, IdentityRole>(identityOptions =>
{
identityOptions.Cookies.ApplicationCookie.AutomaticChallenge = false;
})
Run Code Online (Sandbox Code Playgroud)
但是,不再Cookies有财产identityOptions.
我也试过添加以下内容(并且还注意到我以前在我的应用中不需要这种扩展方法):
services.AddCookieAuthentication(cookieAuthenticationOptions => {
cookieAuthenticationOptions.LoginPath = ""; // also tried null
cookieAuthenticationOptions.AccessDeniedPath = ""; // also tried null
cookieAuthenticationOptions.LogoutPath = ""; // also tried null
});
Run Code Online (Sandbox Code Playgroud)
该代码似乎对默认重定向路径或行为没有影响.如何在Core 2.0中阻止这些重定向?
我是ASP.NET核心的新手.但是,我在ASP.NET Core 2.0中创建WebAPI.我已经配置了基于JWT Bearer Token的身份验证.下面是我的Controller返回令牌.
[AllowAnonymous]
[Route("api/[controller]")]
public class TokenController : Controller
{
private readonly UserManager<UserEntity> userManager;
private readonly SignInManager<UserEntity> signInManager;
public TokenController(UserManager<UserEntity> userManager, SignInManager<UserEntity> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
// GET: api/values
[HttpGet]
public async Task<IActionResult> Get(string username, string password, string grant_type)
{
{
var user = await userManager.FindByEmailAsync(username);
if (user != null)
{
var result =await signInManager.CheckPasswordSignInAsync(user, password, false);
if (result.Succeeded)
{
var claims = new[]
{
new Claim( JwtRegisteredClaimNames.Sub, username),
new Claim( JwtRegisteredClaimNames.Jti, …Run Code Online (Sandbox Code Playgroud) bearer-token asp.net-core-webapi asp.net-core-identity asp.net-core-2.0
让我们暂时离开ASP.NET身份,让我们假设我们正在为我们的应用程序构建自定义身份验证/授权系统.
它将包含以下表格以获得完全的灵活性:
用户
角色
权限
UserRoles
RolePermissions
通过上述内容,我们可以拥有应用程序的完整用户管理部分,其中管理员可以说用户A具有角色B,其具有权限C,D,F.
上面的内容在过去一直对我有用,但现在可以使用ASP.NET Identity切换到ASP.NET Core MVC应用程序.
尝试利用Microsoft在UserManager中为您提供ASP.NET核心身份的一切我希望能够仍然实现上述目标,但是ASP.NET核心身份MVC方式.
我所知道的:
我可以轻松使用UserManager为用户和角色以及用户角色实现CRUD页面.
我想弄清楚:
我怎样才能复制"角色拥有哪些权限/操作?"的相同行为.概念.
我最初的猜测是你会将Claim与Roles结合使用.声明被分配给角色,即RoleClaims,然后角色被分配给用户.
通过这种方式,我可以使用Authorize标签检查控制器/操作方法之上的角色.另外在页面级别更进一步说如果用户的角色没有声明隐藏/显示删除按钮声明"DeleteProduct"有点像这个基于视图的授权文档所说的那样.
-
我试图弄清楚我是否正在使用这些东西走上正确的道路.任何建议或更正都会有所帮助.
c# asp.net asp.net-identity asp.net-core asp.net-core-identity
我有以下代码.我试图为创建用户运行一个测试用例.以下是我到目前为止所尝试的.
public class CreateUserCommandHandlerTest
{
private Mock<UserManager<ApplicationUser>> _userManager;
private CreateUserCommandHandler _systemUnderTest;
public CreateUserCommandHandlerTest()
{
_userManager = MockUserManager.GetUserManager<ApplicationUser>();
var user = new ApplicationUser() { UserName = "ancon1", Email = "ancon@mail.com", RoleType = RoleTypes.Anonymous };
_userManager
.Setup(u => u.CreateAsync(user, "ancon2")).ReturnsAsync(IdentityResult.Success);
_systemUnderTest = new CreateUserCommandHandler(_userManager.Object);
}
[Fact]
public async void Handle_GivenValidInput_ReturnsCreatedResponse()
{
var command = new CreateUserCommand { Username = "ancon1", Email = "ancon@mail.com", Password = "ancon2", RoleType = RoleTypes.Anonymous };
var result = await _systemUnderTest.Handle(command, default(CancellationToken));
Assert.NotNull(result);
Assert.IsType<Application.Commands.CreatedResponse>(result);
}
}
Run Code Online (Sandbox Code Playgroud)
我的用户经理在这里:
public …Run Code Online (Sandbox Code Playgroud) 我使用了User从IdentityUserusing派生的自定义实现Asp.Net Core Identity:
public class AppUser : IdentityUser
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果我调用该方法:
var identityResult = await UserManager.CreateAsync(user);
Run Code Online (Sandbox Code Playgroud)
我收到错误:
System.InvalidOperationException:无法跟踪“AppUser”类型的实体,因为主键属性“Id”为空。
它的工作原理完全符合的版本Microsoft.AspNetCore.Identity.EntityFrameworkCore- 2.2.0,但升级后3.0.0-这是行不通的。
我在测试用户创建过程中也遇到同样的错误,我使用以下UserManager配置:
我在开发应用程序时遇到了这个问题,但没有找到与之相关的任何问题。
我正在使用 asp.net Core 3.1,win 10。
我正在尝试实现为多租户应用程序处理SSO的IdentityServer。我们的系统将只有一个IdentityServer4实例来处理多租户客户端的身份验证。
在客户端,我正在使用acr_value传递租户ID。来自Startup.cs文件的一段代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthorization();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "Client1";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("openid");
options.Scope.Add("profile");
options.Scope.Add("offline_access");
options.Events.OnRedirectToIdentityProvider = n =>
{
if (n.ProtocolMessage.RequestType ==
OpenIdConnectRequestType.Authentication)
{
n.ProtocolMessage.AcrValues = "tenant:clientId1";
}
return Task.FromResult(0);
};
});
}
Run Code Online (Sandbox Code Playgroud)
对于身份服务器,使用具有ASP.NET Core身份的IdentityServer4。为了处理多租户客户端身份验证,我按照本文中Scott Brady针对ASP.NET Identity给出的说明进行操作:https : //www.scottbrady91.com/ASPNET-Identity/Quick-and-Easy-ASPNET-Identity-Multitenancy …
c# multi-tenant asp.net-core identityserver4 asp.net-core-identity
我有一个运行 .net core 2.x 的 Web 应用程序(最终刚刚从 .net core 1.x 升级),并且我已经将大部分内容从 .net core 1.x 移植到 2.x。然而,我的身份实现遇到了砖墙。它在 .net core 1.x 上运行良好,但现在它拒绝了。
该实现在 Entity Framework Core 上运行,并首先构建数据库(在预先存在的数据库中实现)。
我的问题是,当我现在尝试使用 .net core 2.x 登录时,我收到一条错误消息,指出:
InvalidOperationException:从 'AspNetUserRole.AspNetRole' 到具有外键属性 {'RoleId' : int} 的 'AspNetUserRole.AspNetRole' 的关系无法定位主键 {'Id' : int},因为它不兼容。为此关系配置一个主键或一组兼容的外键属性。
对我来说,这完全没有意义。int外键如何与int主键不兼容?
上下文和类的实际实现如下(这是一个非常简单的实现):
public partial class AspNetUser : IdentityUser<int>
{ }
public partial class AspNetRole : IdentityRole<int>
{ }
public partial class AspNetRoleClaim : IdentityRoleClaim<int>
{ }
public partial class AspNetUserClaim : IdentityUserClaim<int>
{ } …Run Code Online (Sandbox Code Playgroud) c# invalidoperationexception entity-framework-core asp.net-core asp.net-core-identity
我有带有 Asp.Net Core Identity 的基本 IdentityServer4。重定向到登录页面并登录后,IdentityServer 不会将我重定向回客户端。
身份服务器配置:
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
RedirectUris = { "http://localhost:50309/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:50309/signout-callback-oidc" },
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = true
}
Run Code Online (Sandbox Code Playgroud)
IdentityServer 启动:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy …Run Code Online (Sandbox Code Playgroud) 知道为什么我会收到此错误吗?错误消息 -->“IServiceCollection 不包含 AddDefaultIdentity 的定义”
我正在从 .NET Core v1.1 迁移到 v3.1
public class Program
{
public async static void Main(string[] args)
{
await Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
webBuilder.UseKestrel();
webBuilder.UseAzureAppServices();
webBuilder.UseStartup<Startup>();
})
.Build()
.RunAsync();
}
}
public class Startup
{
public Startup(IConfiguration configuration, IHostEnvironment hostEnvironment)
{
Configuration = configuration;
HostEnvironment = hostEnvironment;
}
public IConfiguration Configuration { get; }
protected IApplicationBuilder ApplicationBuilder { get; private set; }
public IHostEnvironment HostEnvironment { get; }
// This method gets called by the …Run Code Online (Sandbox Code Playgroud) asp.net-core ×8
c# ×5
.net-core ×1
asp.net ×1
bearer-token ×1
cookies ×1
mocking ×1
multi-tenant ×1
unit-testing ×1