我写了一个asp.net core 3.0 web api,我使用 JWT 令牌来验证用户。一旦用户获得令牌,他/她就可以使用它直到它到期。
我所做的是,我还在身份验证时将此令牌存储在内存中,以获取其他最少的详细信息,例如用户名、生成的令牌和“令牌”。
我的第一个问题是这是一个好的做法吗?由于令牌是无状态的,因此可以使服务器端免于维护它的麻烦。
我的第二个问题是,如果这样做是可以接受的,那么一旦令牌过期,我如何从内存中删除此令牌信息。
如果我没有将此令牌存储在内存中,如何提取诸如“获取所有登录用户的列表”之类的信息。
我正在尝试使用 nestJS 了解 jwt 和身份验证。我创建了两个单独的微服务,其中一个是身份验证服务,成功登录后,客户端获得 jwt 令牌,使用此令牌他可以访问另一个微服务。
这是 auth 服务的 JwtStrategy 和 AuthModule 的代码:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'secretKey'
});
}
async validate(payload: any) {
return payload;
}
}
Run Code Online (Sandbox Code Playgroud)
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { UsersModule } from '../users/users.module';
import { PassportModule …Run Code Online (Sandbox Code Playgroud) 我正在为应用程序使用Firebase身份验证,但作为用户创建的一部分,我需要设置一些自定义声明。
我编写了一个云函数来在创建用户时设置声明:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// On sign up.
exports.processSignUp = functions.auth.user().onCreate(user => {
let customClaims;
// Set custom user claims on this newly created user.
return admin.auth().setCustomUserClaims(user.uid, {
'https://hasura.io/jwt/claims': {
'x-hasura-default-role': 'user',
'x-hasura-allowed-roles': ['user'],
'x-hasura-user-id': user.uid
}
})
.then(() => {
// Update real-time database to notify client to force refresh.
const metadataRef = admin.database().ref("metadata/" + user.uid);
// Set the refresh time to the current UTC timestamp.
// This will be …Run Code Online (Sandbox Code Playgroud) jwt firebase-authentication flutter google-cloud-functions jwt-auth
我正在尝试创建一个手动令牌,我想添加过期时间。从这里 =>文档
这里=>
from rest_framework_simplejwt.tokens import RefreshToken
refresh = RefreshToken.for_user(user)
refresh.set_exp(lifetime=datetime.timedelta(days=10))
# refresh.lifetime = datetime.timedelta(days=10)
return Response ({
'access': str(refresh.access_token),'refresh':str(refresh),"status":"success"
})
Run Code Online (Sandbox Code Playgroud)
这是setting.py=>
JWT_AUTH = {
# how long the original token is valid for
'ACCESS_TOKEN_LIFETIME': datetime.timedelta(days=2),
# allow refreshing of tokens
'JWT_ALLOW_REFRESH': True,
# this is the maximum time AFTER the token was issued that
# it can be refreshed. exprired tokens can't be refreshed.
'REFRESH_TOKEN_LIFETIME': datetime.timedelta(days=7),
}
Run Code Online (Sandbox Code Playgroud)
但是为什么即使我添加了 10 天,这个访问令牌也会在 5 分钟后过期?如何添加过期时间?
创建此方法是为了使用电子邮件和密码进行身份验证。因为默认身份验证使用用户 ID 和密码。有没有办法在 drf 示例 jwt …
使用 Postman 测试我的端点,我能够成功“登录”并接收 JWT 令牌。现在,我正在尝试访问一个据称具有 的端点,AuthGuard以确保现在我已登录,我现在可以访问它。
但是,401 Unauthorized即使在 Postman 中提供 JWT 令牌,它也会不断返回。
这是我的代码:
用户控制器.ts
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@UseGuards(AuthGuard())
@Get()
getUsers() {
return this.usersService.getUsersAsync();
}
}
Run Code Online (Sandbox Code Playgroud)
jwt.strategy.ts
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly authenticationService: AuthenticationService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: 'SuperSecretJWTKey',
});
}
async validate(payload: any, done: Function) {
console.log("I AM HERE"); // this never gets called.
const user = await this.authenticationService.validateUserToken(payload);
if …Run Code Online (Sandbox Code Playgroud) 我在 Laravel 5.6 项目中使用 JWT-Auth 包。
我有一个使用 getPayload 方法的简单测试,但它不断返回;
Tymon\JWTAuth\Exceptions\JWTException: A token is required
Run Code Online (Sandbox Code Playgroud)
到目前为止,我的方法如下;
$user = factory(User::class)->create();
$token = JWTAuth::fromUser($user);
$payload = JWTAuth::getPayload($token);
Run Code Online (Sandbox Code Playgroud)
如果我这样做,dd($token)它会正确地吐出用户令牌。
如果其他人遇到了这个问题,我希望得到一些帮助。
干杯
我正在尝试实现对所有 API 调用都需要 JWT 身份验证的 API 服务的使用。
我了解 JWT 令牌是什么以及它们是如何使用的,我的问题是我正在编写一个 Swift 应用程序并且无法弄清楚生成令牌的过程,以便我可以将它作为BearerAPI 调用中的一个附加。
尝试使用 tymon/jwt-auth (JWT) 在 laravel 安装中实现登录端点。登录、注销、获取用户数据工作正常。我想要一个端点来检查承载令牌。有一种简短的方法可以通过以下方式实现这一目标:
Route::get('/valid', function () {
return 1;
})->middleware('auth:api');
Run Code Online (Sandbox Code Playgroud)
如果令牌有效,则 HTTP 返回代码 == 200,但如果无效,则返回 401 代码。由于端点正在检查令牌而不是经过身份验证的通信,我宁愿让控制器返回真/假关于有效令牌的 200 - OK。
我查看了模块的“幕后”,这就是我得到的程度(不工作):
$tokenKey = $request->bearerToken();
$jws = \Namshi\JOSE\JWS::load($tokenKey);
$jwsSimple = new SimpleJWS($jws->getHeader());
$jwsSimple::load($tokenKey);
$jwsSimple->setPayload($jws->getPayload());
$jwsSimple->setEncodedSignature(explode('.', $tokenKey)[2]);
$tmpVal = $jwsSimple->isValid($tokenKey);
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现这一目标?我认为应该有一个服务提供商,但无法弄清楚如何实现这一点。先感谢您。
使用 Lumen 从 JWT 获取一些错误:
无法创建令牌:不推荐从字符串中隐式转换键。请使用 InMemory 或 LocalFileReference 类
https://github.com/tymondesigns/jwt-auth/issues/2059
任何关于快速修复的建议,这似乎是新版本中的错误。
以下是我正在使用的JWT身份验证:
.AddJwtBearer(options =>
{
// options.SaveToken = false;
// options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(AuthConfig.GetSecretKey(Configuration)),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
};
options.Events = new JwtBearerEvents()
{
OnChallenge = c =>
{
c.HandleResponse();
// TODO: How to know if the token was expired?
return AspNetUtils.WriteJsonAsync(c.Response, new Result<string>
{
Message = "Unauthenticated.",
IsError = true
}, 401);
},
};
});
Run Code Online (Sandbox Code Playgroud)
身份验证正常。对于新要求,我需要知道是否由于JWT令牌过期而导致身份验证失败。
请注意,身份验证失败可能有多种原因。令牌可能丢失,被篡改或过期。
有任何想法吗?谢谢!
jwt-auth ×10
jwt ×6
asp.net-core ×2
laravel ×2
nestjs ×2
passport.js ×2
flutter ×1
laravel-5 ×1
lumen ×1
passport-jwt ×1
php ×1
swift ×1