- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在使用 .net core 2.0 运行的 Web-API 中实现了 JWT Bearer Token- Authentication。现在我创建了另一个与我的 Web-API 对话的网站。检索 token 有效,我将其添加到 cookie 中,在调试时我可以看到我的 cookie(名称为“身份”)具有正确的值。
在项目模板中有 Controller HomeController
和操作。我出于我的目的使用操作 Contact
并使用 AuthorizeAttribute
对其进行注释:
[Authorize]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
现在我正在导航(作为匿名用户)到 /home/contact
- 完美:它将我重定向到我需要登录的 /home/login
。
当我尝试登录时,出现以下错误消息:
No IAuthenticationSignInHandler is configured to handle sign in for the scheme: Bearer
我想 token 配置是错误的 - 我想我在这里做错了一些事情。
首先,这是我的Startup.cs(我没有删除任何东西,因为顺序有依赖性):
public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true;
});
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("mysupersecret_secretkey!123")),
ValidateIssuer = true,
ValidIssuer = "ExampleIssuer",
ValidateAudience = true,
ValidAudience = "ExampleAudience",
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
SaveSigninToken = true
};
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
JwtSecurityToken accessToken = context.SecurityToken as JwtSecurityToken;
if (accessToken != null)
{
ClaimsIdentity identity = context.Result.Principal.Identity as ClaimsIdentity;
identity?.AddClaim(new Claim("access_token", accessToken.RawData));
}
return Task.CompletedTask;
}
};
})
.AddCookie(
o =>
{
o.Cookie.Name = "beareridentity";
o.LoginPath = new PathString("/Home/Login/");
o.AccessDeniedPath = new PathString("/Home/Login/");
});
services.AddMvc();
services.AddTransient<IAccountService, AccountService>();
services.AddTransient(typeof(ISession), serviceProvider =>
{
var httpContextAccessor = serviceProvider.GetService<IHttpContextAccessor>();
return httpContextAccessor.HttpContext.Session;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseSession();
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
这是我的登录操作:
[HttpPost]
public async Task<IActionResult> Login(LoginData data)
{
var loginresult = (await _accountService.GetLoginToken(data.Username, data.Password));
if (!loginresult.Success)
return RedirectToAction("Login");
Response.Cookies.Append("identity", loginresult.Token, new CookieOptions { Expires = DateTimeOffset.Now.Add
int id = await _getIdFromToken(loginresult);
ApplicationUser user;
await _signin(user = await _accountService.GetUserAsync(id));
_session.SetData("actualuser", user);
return RedirectToAction("Index");
}
private async Task _signin(ApplicationUser c)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.MobilePhone, c.Phone??""),
new Claim(ClaimTypes.Name, c.UserName)
};
var userIdentity = new ClaimsIdentity();
userIdentity.AddClaims(claims);
ClaimsPrincipal userPrincipal = new ClaimsPrincipal(userIdentity);
try
{
await HttpContext.SignInAsync(
JwtBearerDefaults.AuthenticationScheme,
userPrincipal,
new Microsoft.AspNetCore.Authentication.AuthenticationProperties
{
ExpiresUtc = DateTime.UtcNow.AddMinutes(20),
IsPersistent = true,
AllowRefresh = true,
IssuedUtc = DateTimeOffset.Now
});
}
catch (Exception e)
{
throw;
}
}
最佳答案
这是一篇关于如何在 ASP.NET Core 2.0 上使用 cookie 作为 JWT 的传递机制的博文,这正是您正在尝试做的事情: JWT Token Authentication with Cookies in ASP.NET Core
我还没有尝试过,但它可以指导您了解哪里可能做错了。
关于c# - AuthorizeAttribute with JWT Token- Authentication in .NET Core 2.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709965/
这是我的 CustomAuthorizeAttribute 类: public class CustomAuthorizeAttribute : AuthorizeAttribute {
TL;博士 :当 IdentityServer3 将表单发布到始终是根 url 的返回 url 时,MVC 应用程序如何知道在通过身份验证过程后重定向到某个操作? 此问题中的示例取自 Identity
在我们的 MVC 解决方案中,我们有两个 AuthorizeAttribute 的自定义实现 - 一个名为 BasicHttpAuthorizeAttribute 并已在生产中使用多年,另一个 Rol
我的应用程序中有一个自定义的 AuthorizeAttribute,它接受一个输入参数 bool UserIsOnline。此参数用于增加一个表字段,该字段包含有关上次用户交互时间的信息,即对于在后台
我有一个 ApiController 类,其中有 10 个公共(public)方法。 在这 10 个方法中,有 9 个需要 [Authorize(Roles="Admin")]。不需要的,不需要任何授
我目前正在尝试根据用户角色在新的 ASP MVC 5 应用程序中实现安全性。目标是防止用户在没有特定角色(或更高级别)的情况下访问某些 Controller 或 Controller 方法。根据到目前
我正忙着为我的名为 MyAuthorizeAttribute 的操作方法编写自己的自定义属性,我还在忙着编写代码,这是我的部分代码: [AttributeUsage(AttributeTargets.
我创建了一个自定义 AuthorizeAttribute 类来处理我的 MVC4 应用程序中的精细授权。 这是类: [AttributeUsage(AttributeTargets.Method, A
我已经从 AuthorizeAttribute 实现了 RoleAuthorize 类 public sealed class RoleAuthorize : AuthorizeAttribute {
我正在使用 MVC3/4。但这只是授权中的一般问题。 我有一个角色在数据库中名为“Trip Leader”,其中包含一个空格。 我尝试了 [Authorize(Roles="'Trip Leader'
我们想授权用户,如果他们被授权,我们想将他们的角色和权限添加到用户并将其添加到 IPrinciple 我们有两种方法可以做到这一点,一种是在 global.asax Application_Authe
我一直在互联网上寻找为什么我的自定义 AuthorizeAttribute 在我的 MVC WebApi 中不起作用。我看到有人在 SO 上问过这种事情,但还没有帮助我解决我的问题: [Attrib
我想使用标准的 AuthorizeAttribute(即不继承它)但使用自定义重定向。那可能吗?我应该在哪里检查 401 并重定向? 我试过添加 但它没有用。 最佳答案 在我的 A
在 Windows 域内网站点(使用 )上工作时,我遇到了以下问题: [Authorize(Roles = "Domain Users, Domain Admins")] public class
我有一个像这样的自定义 AuthorizeAttribute public class DevMode : AuthorizationFilterAttribute { public over
我试图阻止特定角色(比如 RoleA)中的特定用户访问特定操作。允许匿名用户访问,但不允许 RoleA 中的用户访问该操作。 所以我做了这样的事情: [AllowAnonymous] [CustomA
如果我做了more than one API调用同时出现错误 A second operation started on this context before a previous asynchro
我有一个自定义的 RequireHttpsAttribute 和一个自定义的 AuthorizeAttribute,我在 FilterConfig 中应用它们以确保所有 Controller 都使用
在我的 MVC 5 应用程序中,我按如下方式装饰我的 Controller : [Authorize] public class Controller { .. 但是,我的一个要求是使用 toke
我已经研究了一段时间,现在试图弄清楚如何在我的 View 中使用我的自定义 AuthorizeAttribute 类来显示和隐藏链接。我正在从 IsInRole 过渡到自定义 AuthorizeAtt
我是一名优秀的程序员,十分优秀!