gpt4 book ai didi

c# - AuthorizeAttribute with JWT Token- Authentication in .NET Core 2.0

转载 作者:太空狗 更新时间:2023-10-29 20:35:56 26 4
gpt4 key购买 nike

我在使用 .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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com