我需要在REST API中使用URI来检索当前登录的用户.通常我GET在具有ID的资源上使用,但客户端不知道用户的ID.
我找到了以下解决方案:
按用户名
此解决方案使用用户名而不是用户的ID.
例:
GET /user/{userSlug}拥有自己的资源
此解决方案为用户提供了一个资源,为登录用户提供了一个额外资源.
例子:
JIRA REST API:GET /myself
GitHub REST API:GET /user
Stack Exchange REST API:GET /me
带有符号链接
该解决方案具有用户ID的符号链接.
例:
GET /user/current带过滤器
此解决方案使用筛选器作为用户名.
例:
GET /user?username={username}哪一个最RESTful?优缺点都有什么?
我想创建一个 NestJs 应用程序,并希望有一个验证请求对象中的令牌的中间件和一个验证令牌有效负载中用户的身份验证守卫。
通过拆分这个,我希望有一个干净的分离。首先是我的中间件
@Injectable()
export class TokenMiddleware implements NestMiddleware {
use(req: any, res: Response, next: NextFunction) {
try {
const headers: IncomingHttpHeaders = req.headers;
const authorization: string = headers.authorization;
const bearerToken: string[] = authorization.split(' ');
const token: string = bearerToken[1];
// !! Check if token was invalidated !!
req.token = token;
req.tokenPayload = verifyToken(token);
next();
} catch (error) {
throw new UnauthorizedException();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它只验证令牌并使用编码的令牌及其有效负载扩展请求对象。我的身份守卫
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(private readonly usersService: UsersService) {}
async …Run Code Online (Sandbox Code Playgroud)