我正在开发Net Core 3.0 Web应用程序和Net Core 3.0 Web API。
Web API在[Authorize]
以外的所有端点上都有login
属性,并且登录成功后会向我发送JWT。但是,我不知道如何将其存储在Web应用程序中以及如何使用它向我的API请求内容。
我当前在Web应用程序中正在做的事情是这样的:
public async Task<ClaimsPrincipal> Login(LoginViewModel model)
{
var response = await Client.PostAsJsonAsync("user/login", model);
// Client is HttpClient
try
{
response.EnsureSuccessStatusCode();
var token = await response.Content.ReadAsAsync<JsonWebToken>();
if (!token.Success)
return null;
var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, token.Email),
...
};
// What do I Have to do with token.Token?
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
return principal;
}
catch (Exception e)
{
Debug.WriteLine(e);
return null;
}
}
然后我登录(/ User / Login)时的[HttpPost]
方法正在执行此操作:
var response = await Login(model)
await HttpContext.SignInAsync(response);
和我的Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o => o.LoginPath = "/User/Login");
使用
app.UseAuthentication();
在Configure
所以现在我可以使用Cookie登录,注销,但我不知道如何存储/使用JWT来调用我的API。 如何为客户指定令牌?
代码示例将非常有帮助。
答案 0 :(得分:0)
如果您使用的是ASP.NET Core API,并且前端是Angular / React / etc,则可以将JWT令牌保存在本地或会话存储中,并将其包含在对API的每个ajax请求中。