我正在尝试在 ASP Net Core 2.1 中使用 Jwt auth 和 Identity
在我的 Startup.cs 中,我有:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
};
});
var builder = services.AddIdentityCore<User>(options =>
{
// Password settings
...
// Lockout settings
...
// User settings
options.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)
builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
然后在 SecurityService.cs 中我尝试使用此语句来获取角色
var roles …Run Code Online (Sandbox Code Playgroud) 我已根据 ASP.NET Core 项目中的 Scaffold Identity 将我的 asp.net core 2.2 应用程序配置为脚手架身份(以便我可以自定义其外观)=>创建完整的身份 UI 源链接。当我直接在浏览器中请求时, http ://localhost:12345/identity/account/login url 有效,但当我将其作为主页上的链接包含时,它不起作用。我究竟做错了什么?
启动.cs:
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 = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<IdentityUser, IdentityRole>()
//.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).
AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Identity/Account/Login";
options.LogoutPath = …Run Code Online (Sandbox Code Playgroud) 我正在使用 ASP.NET Core 2.2,我需要在我的应用程序中生成自定义令牌。
Asp.Net Core Identity UserManager 可以生成经典令牌,例如 EmailVerification,...
但它还有一种生成具有不同用途的令牌的方法(MSFT Docs):
public virtual System.Threading.Tasks.Task<string> GenerateUserTokenAsync (TUser user, string tokenProvider, string purpose);
Run Code Online (Sandbox Code Playgroud)
我需要生成包含以下信息的令牌:
在GenerateUserTokenAsync上我可以添加用户和目的......
但我不知道如何添加(3)和(4),例如ProjectId和RoleId。
我怎样才能稍后检索它以便我可以实际执行该操作。
我该怎么做?
usermanager asp.net-core asp.net-core-identity asp.net-core-2.2
情况
我正在使用 Identity ASP.NET Core 3.1 和 Angular 8 模板。我想扩展 ASPNETUserRoles 表并在其中添加另一个自定义键列 CompanyId。
默认情况下,身份提供:
public virtual TKey UserId { get; set; }
public virtual TKey RoleId { get; set; }
Run Code Online (Sandbox Code Playgroud)
当我将 DbContext 从 UserId(字符串)修改为 UserId(长整型)时,DbContext 看起来像:
public class CompanyDBContext : KeyApiAuthorizationDbContext<User, Role, UserRole, long>
{
public CompanyDBContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public DbSet<Company> Companies { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
KeyApiAuthorizationDbContext
public class KeyApiAuthorizationDbContext<TUser, TRole, IdentityUserRole, TKey> : …Run Code Online (Sandbox Code Playgroud) asp.net-mvc entity-framework entity-framework-core asp.net-core asp.net-core-identity
我正在使用 .NET 版本5.0.100-rc.1.20452.10、ASP.NET Core Web API、Microsoft SQL Server 2019、JWT 令牌。我有Startup.cs
using Microsoft.AspNetCore.Authentication.JwtBearer;\nusing Microsoft.AspNetCore.Authorization;\nusing Microsoft.AspNetCore.Builder;\nusing Microsoft.AspNetCore.Hosting;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Identity;\nusing Microsoft.EntityFrameworkCore;\nusing Microsoft.Extensions.Configuration;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.FileProviders;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.IdentityModel.Tokens;\nusing shadow.Data;\nusing shadow.Models;\nusing shadow.Services;\nusing System.IO;\nusing System.Text;\n\nnamespace shadow\n{\n public class Startup\n {\n public Startup(IConfiguration configuration)\n {\n Configuration = configuration;\n }\n\n public IConfiguration Configuration { get; }\n\n public void ConfigureServices(IServiceCollection services)\n {\n services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));\n services.AddHttpContextAccessor();\n //services.AddCors();\n services.AddCors(options =>\n {\n options.AddPolicy("CorsPolicy",\n builder => builder.AllowAnyOrigin()\n .AllowAnyMethod()\n .AllowAnyHeader());\n });\n services.AddSingleton<IUriService>(o =>\n {\n var accessor = o.GetRequiredService<IHttpContextAccessor>();\n var request …Run Code Online (Sandbox Code Playgroud) c# jwt asp.net-core asp.net-core-webapi asp.net-core-identity
我正在创建一个服务,它将以 Asp.Net Core 作为后端,以 Angular 作为前端。我正在微软为 SPA 提供的不同模板上测试一些内容。
因此,我使用 .Net core 5 cli 使用此命令创建了一个:
dotnet new angular -au Individual
Run Code Online (Sandbox Code Playgroud)
似乎可行,但我的理解是,当我需要将用户重定向到加载页面时(因为未连接或没有足够的权限),我将被重定向到 Asp.Net Core 页面的 UI。
我已经看到我可以自定义此页面(好吧,创建一个脚手架版本并自定义它),但它仍然让我担心:
所以我的问题是,如何对使用 asp.net core 身份的 Asp.Net core 服务器进行身份验证?
single-page-application .net-core asp.net-core asp.net-core-identity angular
我正在使用 ASP.NET Core MVC 构建一个网站。我搭建了身份页面,并尝试将名字和姓氏属性添加到注册表中。我被困在根据表单输入设置用户名字/姓氏的位置上。下面是Register.cshtml.cs我搭建的文件。
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
namespace IssueTracker.Areas.Identity.Pages.Account
{
public class RegisterModel : PageModel
{
private readonly SignInManager<IdentityUser> _signInManager;
private readonly …Run Code Online (Sandbox Code Playgroud) 我的 PC 上有 ASP.NET Core 项目,那里的一切都运行良好。
最近,我将 SQL 数据库从 PC 转移到笔记本电脑上,看看如果我将项目发送给某人会发生什么。我有两个数据库,但在这个问题中,我想重点关注存储用户信息的数据库。
当我尝试使用 PC 上的帐户登录时,一切正常,并且我能够登录到我的帐户,但是当我尝试在笔记本电脑上执行相同操作时,我得到的是Invalid Login Attempt,这是检查登录的函数:
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/");
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
if (result.Succeeded)
{
_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", …Run Code Online (Sandbox Code Playgroud) 在我们的ASP.NET MVC Core应用程序中,我们使用ASP.NET Idenity来实现用户管理。
问题:如何使用ASP.NET用户界面,而不是直接使用SQL语句等在SQL数据库中创建用户?直接在ASPNETUsers表中创建用户会引起任何问题吗?注意:我们需要ASPNETUsers从用户列表中填充内置身份表。密码可以是任何东西,不需要任何特定角色。
sql-server asp.net-identity asp.net-core asp.net-core-identity
我想对控制器上的所有操作都要求一个策略,并且对HTTP“编辑方法”(POST,PUT,PATCH和DELETE)的所有调用都需要第二个策略。也就是说,编辑方法应同时要求两个策略。由于实现要求,以及保持代码DRY的愿望,我需要将后者策略应用于控制器级别,而不是在所有操作方法上都重复使用。
举一个简单的例子,我有一个PeopleController,我也有两个许可权,分别实现为Policy ViewPeople和EditPeople。现在我有:
[Authorize("ViewPeople")]
public class PeopleController : Controller { }
Run Code Online (Sandbox Code Playgroud)
如何添加EditPeople策略/权限,使其“堆叠”且仅适用于编辑动词?
我遇到了两个似乎都是很痛苦的问题:
我尝试使用自定义Requirement和AuthorizationHandler解决前者,如下所示:
public class ViewEditRolesRequirement : IAuthorizationRequirement
{
public ViewEditRolesRequirement(Roles[] editRoles, Roles[] viewRoles)
=> (EditRoles, ViewRoles) = (editRoles, viewRoles);
public Roles[] EditRoles { get; }
public Roles[] ViewRoles { get; }
}
public class ViewEditRolesHandler : AuthorizationHandler<ViewEditRolesRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, ViewEditRolesRequirement requirement)
{
if (context.User != null)
{
var canView = requirement.ViewRoles.Any(r => context.User.IsInRole(r.ToString()));
var …Run Code Online (Sandbox Code Playgroud) asp.net-core ×9
c# ×6
jwt ×2
.net-core ×1
angular ×1
asp.net-mvc ×1
sql-server ×1
usermanager ×1