Mat*_*ger 7 c# jwt asp.net-web-api asp.net-core
我在使用.net core 2.0运行的Web-API中实现了JWT Bearer Token-Authentication.现在我创建了另一个与我的Web-API对话的网站.检索令牌有效,我将其添加到cookie中,当我调试时,我可以看到我的cookie(名称是"identity")具有正确的值.
在项目模板中,有一个HomeController带有操作的控制器.我正在使用该操作Contact用于我的目的并使用以下内容对其进行注释AuthorizeAttribute:
[Authorize]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
Run Code Online (Sandbox Code Playgroud)
现在我正在浏览(作为匿名用户)/home/contact- 完美:它将我重定向到/home/login我需要登录的位置.
当我尝试登录时,我收到以下错误消息:
没有IAuthenticationSignInHandler配置为处理该方案的登录:承载
我猜令牌配置是错误的 - 我想还有一些我在这里做错的事情.
首先,这是我的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?}");
});
}
Run Code Online (Sandbox Code Playgroud)
这是我的登录动作:
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一篇关于如何在 ASP.NET Core 2.0 上使用 cookie 作为 JWT 的传递机制的博客文章,这正是您想要做的: JWT Token Authentication with Cookies in ASP.NET Core
我还没有尝试过,但它可以指导您了解哪里可能做错了。
| 归档时间: |
|
| 查看次数: |
3829 次 |
| 最近记录: |