使用JWT登录Rest API时保存数据



我目前正在为大学做一个项目。我必须创建一个rest接口和一个身份验证。我已经用Micronaut创建了Rest界面。对于登录和身份验证,我使用了JsonWebToken(JWT(。要登录到系统,您必须输入用户名和密码。在登录的其余时间点,将从数据库中提取数据用户名和密码,并在合适的情况下进行比较。(安全性不那么重要,项目的重点不同(但如果我想预订一张卡(这就是项目的目的(,我必须在交易中保存用户。现在的问题是我如何才能做到最好。如果我用用户名保存一个cookie,并在预订时再次读出,会是最好的吗?我对JWT了解不多,所以另一个问题是,我可以解码令牌并从中提取用户名吗?

有没有其他方法更适合这种情况?我可以使用Micronaut JWT在响应中返回UserID吗?不幸的是,我在这些例子中找不到任何东西。

@Singleton
public class LoginApi implements AuthenticationProvider{
private WebLoginService webLoginService = ServiceLocator.getWebLoginService();
@Override
public Publisher<AuthenticationResponse> authenticate(HttpRequest<?> httpRequest, AuthenticationRequest<?, ?> authenticationRequest) {
return Flux.create(emitter -> {
CustomerID customerID = webLoginService.tryToLogIn((String) authenticationRequest.getIdentity(), (String) authenticationRequest.getSecret());
if(customerID != null && customerID.customerID() != null) {
emitter.next(AuthenticationResponse.success((String) customerID.customerID()));
emitter.complete();
} else {
emitter.error(AuthenticationResponse.exception());
}
}, FluxSink.OverflowStrategy.ERROR);
}
}

如果我用用户名保存一个cookie并读出它会是最好的吗预订时再次预订?

可能不是。如果您想要的是用户名,最好从SecurityServicePrincipalAuthentication对象中检索,如中所述https://micronaut-projects.github.io/micronaut-security/3.2.1/guide/#retrievingAuthenticatedUser.

最新更新