- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我读了几篇文章说本地存储不是存储 JWT token 的首选方式,因为它不适合用于 session 存储,因为您可以通过 JavaScript 代码轻松访问它,这可能会导致 XSS 本身,如果有的话易受攻击的第三方库或其他东西。
从这些文章中总结,正确的方法是使用 HttpOnly cookie 而不是本地存储 session /敏感信息。
我找到了一种 cookie 服务,就像我目前用于本地存储的服务一样。我不清楚的是 expires=Thu, 1 Jan 1990 12:00:00 UTC;路径=/
;`。它真的必须在某个时候过期吗?我只需要存储我的 JWT 和刷新 token 。全部信息都在里面。
import { Injectable } from '@angular/core';
/**
* Handles all business logic relating to setting and getting local storage items.
*/
@Injectable({
providedIn: 'root'
})
export class LocalStorageService {
setItem(key: string, value: any): void {
localStorage.setItem(key, JSON.stringify(value));
}
getItem<T>(key: string): T | null {
const item: string | null = localStorage.getItem(key);
return item !== null ? (JSON.parse(item) as T) : null;
}
removeItem(key: string): void {
localStorage.removeItem(key);
}
}
import { Inject, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class AppCookieService {
private cookieStore = {};
constructor() {
this.parseCookies(document.cookie);
}
public parseCookies(cookies = document.cookie) {
this.cookieStore = {};
if (!!cookies === false) { return; }
const cookiesArr = cookies.split(';');
for (const cookie of cookiesArr) {
const cookieArr = cookie.split('=');
this.cookieStore[cookieArr[0].trim()] = cookieArr[1];
}
}
get(key: string) {
this.parseCookies();
return !!this.cookieStore[key] ? this.cookieStore[key] : null;
}
remove(key: string) {
document.cookie = `${key} = ; expires=Thu, 1 jan 1990 12:00:00 UTC; path=/`;
}
set(key: string, value: string) {
document.cookie = key + '=' + (value || '');
}
}
查看注销函数 signOut()
。在后端撤销JWT token(后端额外订阅)不是更好的做法吗?
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { map, Observable, of } from 'rxjs';
import { JwtHelperService } from '@auth0/angular-jwt';
import { environment } from '@env';
import { LocalStorageService } from '@core/services';
import { AuthResponse, User } from '@core/types';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private readonly ACTION_URL = `${environment.apiUrl}/Accounts/token`;
private jwtHelperService: JwtHelperService;
get userInfo(): User | null {
const accessToken = this.getAccessToken();
return accessToken ? this.jwtHelperService.decodeToken(accessToken) : null;
}
constructor(
private httpClient: HttpClient,
private router: Router,
private localStorageService: LocalStorageService
) {
this.jwtHelperService = new JwtHelperService();
}
signIn(credentials: { username: string; password: string }): Observable<AuthResponse> {
return this.httpClient.post<AuthResponse>(`${this.ACTION_URL}/create`, credentials).pipe(
map((response: AuthResponse) => {
this.setUser(response);
return response;
})
);
}
refreshToken(): Observable<AuthResponse | null> {
const refreshToken = this.getRefreshToken();
if (!refreshToken) {
this.clearUser();
return of(null);
}
return this.httpClient.post<AuthResponse>(`${this.ACTION_URL}/refresh`, { refreshToken }).pipe(
map((response) => {
this.setUser(response);
return response;
})
);
}
signOut(): void {
this.clearUser();
this.router.navigate(['/auth']);
}
getAccessToken(): string | null {
return this.localStorageService.getItem('accessToken');
}
getRefreshToken(): string | null {
return this.localStorageService.getItem('refreshToken');
}
hasAccessTokenExpired(token: string): boolean {
return this.jwtHelperService.isTokenExpired(token);
}
isSignedIn(): boolean {
return this.getAccessToken() ? true : false;
}
private setUser(response: AuthResponse): void {
this.localStorageService.setItem('accessToken', response.accessToken);
this.localStorageService.setItem('refreshToken', response.refreshToken);
}
private clearUser() {
this.localStorageService.removeItem('accessToken');
this.localStorageService.removeItem('refreshToken');
}
}
我的后端是 ASP.NET Core 5,我使用的是 IdentityServer4。我不确定是否必须让后端验证 cookie 或者它是如何工作的?
services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
options.EmitStaticAudienceClaim = true;
})
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Configuration.GetIdentityResources())
.AddInMemoryApiScopes(Configuration.GetApiScopes(configuration))
.AddInMemoryApiResources(Configuration.GetApiResources(configuration))
.AddInMemoryClients(Configuration.GetClients(configuration))
.AddCustomUserStore();
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = configuration["AuthConfiguration:ClientUrl"];
options.RequireHttpsMetadata = false;
options.RoleClaimType = "role";
options.ApiName = configuration["AuthConfiguration:ApiName"];
options.SupportedTokens = SupportedTokens.Jwt;
options.JwtValidationClockSkew = TimeSpan.FromTicks(TimeSpan.TicksPerMinute);
});
最佳答案
您希望后端使用刷新 token 设置 HttpOnly cookie。因此,您将拥有一个 POST 端点,您可以在其中发布您的用户凭据,并且该端点在 HttpOnly cookie 中返回刷新 token ,并且 accessToken 可以作为常规 JSON 属性在请求正文中返回。下面是如何设置 cookie 响应的示例:
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Expires = DateTime.UtcNow.AddDays(7),
SameSite = SameSiteMode.None,
Secure = true
};
Response.Cookies.Append("refreshToken", token, cookieOptions);
一旦您拥有带刷新 token 的 HttpCookie,您就可以将其传递到专用 API 端点以轮换访问 token 。该端点实际上还可以将刷新 token 旋转为 security best practice .以下是检查请求中是否包含 HttpCookie 的方法:
var refreshToken = Request.Cookies["refreshToken"];
if (string.IsNullOrEmpty(refreshToken))
{
return BadRequest(new { Message = "Invalid token" });
}
您的访问 token 应该是短暂的,例如 15-20 分钟。这意味着您希望在它过期前不久主动轮换它,以确保经过身份验证的用户不会注销。您可以使用 setInterval JavaScript 中的函数来构建此刷新功能。
您的刷新 token 可以存在更长时间,但它不应该不会过期。此外,如第 2 点所述,在访问 token 刷新时轮换刷新 token 是一个非常好的主意。
您的访问 token 不需要像本地/ session 存储或 cookie 那样存储在任何地方。您可以简单地将它保存在某个 SPA 服务中,只要不重新加载单个页面,该服务就会存在。如果它由用户重新加载,您只需在初始加载期间轮换 token (记住 HttpOnly cookie 固定在您的域中,并且可以作为资源提供给您的浏览器),一旦您拥有访问 token ,您就可以将其放入每个后端请求的授权 header .
您需要在某处(关系数据库或键值存储)持久保存已发布的刷新 token ,以便能够验证它们、跟踪过期情况并在需要时撤销。
关于angular - 将 JWT token 存储到 HttpOnly cookie 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68777033/
在我的主要组件中,我有: mounted() { window.$cookie.set('cookie_name', userName, expiringTime); }, 这会产生以下错误:
我正在学习 cookie,并且我想知道在编写依赖 cookie 来存储状态的 Web 应用程序时浏览器的支持情况。 对于每个域/网站,可以向浏览器发送多少个 Cookie,大小是多少? 如果发送并存储
我已经为我的站点设置了一个 cdn,并将其用于 css、js 和图像。 网站只提供那些文件 我的问题是 firefox 中的页面速度插件对于我的图片请求,我看到了一个 cookie Cookie fc
在阅读了 Internet 上的文档和帖子后,我仍然无法解决 jMeter 中的 Cookie Manager 问题。 我在响应头中得到了 sid ID,但它没有存储在我的 cookie 管理器中。
我正在 Node.JS 中处理一些类似浏览器的 cookie 处理,想知道从 NodeJS and HTTP Client - Are cookies supported? 开始对这段代码进行扩展到什
我正在此堆栈上构建自托管 Web 服务器:欧文南希网络 API 2 我正在使用 Katana 的 Microsoft.Owin.Security.Cookies 进行类似表单的身份验证。我得到了 Se
我有一个从另一个网站加载资源的网站。我已经能够确定: 第三方网站在用户的浏览器上放置 cookie。 如果我在浏览器设置中禁用第三方 cookie,第三方网站将无法再在浏览器上放置 cookie。 该
关闭。这个问题是off-topic .它目前不接受答案。 想改善这个问题吗? Update the question所以它是 on-topic对于堆栈溢出。 9年前关闭。 Improve this q
我正在使用 python mechanize 制作登录脚本。我已经读到 Mechanize 的 Browser() 对象将自动处理 cookie 以供进一步请求。 我怎样才能使这个 cookie 持久
我正在尝试在 www.example.com 和 admin.other.example.com 之间共享 cookie 我已经能够使其与 other.example.com 一起使用,但是无法访问子
我设置了一个域为 .example.com 的 cookie .它适用于我网站上的每个一级子域,应该如此。 但是,它不适用于 n 级子域,即 sub.subdomain.example.com和 to
我想让用户尽可能长时间地登录。 我应该使用什么? 普通 cookies 持久性 cookie 快闪 cookies ip地址 session 或这些的某种组合? 最佳答案 我认为 Flash cook
如果给定的 Web 服务器只能读取其域内设置的 cookie,那么 Internet 广告商如何从其网络外的网站跟踪用户的 Web 流量? 是否存在某种“supercookie”全局广告系统,允许广告
我知道一个 cookie 可以容纳多少数据是有限制的,但是我们可以设置多少个 cookie 有限制吗? 最佳答案 来自 http://www.ietf.org/rfc/rfc2109.txt Prac
如果我拒绝创建 cookie,则在我的浏览器中创建名称为 __utma、__utmb 等的 cookie。我认为这个 cookie 是用于谷歌分析的。任何人都知道谷歌如何创建这个 cookie,即使浏
我有一个生产环境和一个登台环境。我想知道我是否可以在环境之间沙箱 cookie。我的设置看起来像 生产 domain.com - 前端 SPA api.domain.com - 后端节点 分期 sta
我想知道浏览器(即 Firefox )和网站的交互。 当我将用户名和密码提交到登录表单时,会发生什么? 我认为该网站向我发送了一些 cookie,并通过检查这些 cookie 来授权我。 cookie
我在两个不同的域中有两个网络应用程序 WebApp1 和 WebApp2。 我在 HttpResponse 的 WebApp1 中设置 cookie。 如何从 WebApp2 中的 HttpReque
我正在使用Dartium“Version 34.0.1847.0 aura(264987)”,并从Dart创建一个websocket。但是,如果不是httpOnly,我的安全 session cook
我从 Headfirst Javascript 书中获取了用于 cookie 的代码。但由于某种原因,它不适用于我的浏览器。我主要使用chrome和ff,并且我在chrome中启用了本地cookie。
我是一名优秀的程序员,十分优秀!