2 回答

TA貢獻(xiàn)1862條經(jīng)驗 獲得超7個贊
如果您仍在尋找解決方案,這就是有效的方法。您必須提供一個實現(xiàn)JwtAuthenticationFactory并替換 default DefaultJwtAuthenticationFactory。
像這樣的東西(下面的代碼在 Kotlin 中):
@Singleton
@Replaces(bean = DefaultJwtAuthenticationFactory::class)
class CustomJwtAuthenticationFactory() : JwtAuthenticationFactory {
override fun createAuthentication(token: JWT?): Optional<Authentication> {
try {
val builder = JWTClaimsSet.Builder()
builder.claim("username", token?.jwtClaimsSet?.getStringClaim("username"))
return Optional.of(AuthenticationJWTClaimsSetAdapter(jwtClaims))
} catch (e: Exception) {
throw RuntimeException("ParseException creating authentication", e)
}
}
}
使用構(gòu)建器添加的所有聲明都將添加到Authentication對象中,并且可以在任何控制器中訪問,例如:
@Get("/hello-world")
fun hello(authentication: Authentication): String =
authentication["username"] as String
如果您使用的是 Kotlin,還可以在 Authentication 方法上添加擴(kuò)展方法以獲取您添加到 Authentication 類的屬性,例如: fun Authentication.username(): String = this.attributes["username"]
注意:username只是一個例子。它可用作name身份驗證實例上的實例變量。

TA貢獻(xiàn)1872條經(jīng)驗 獲得超4個贊
UserDetails 認(rèn)證后不存在。唯一可用的對象是身份驗證。如果您想標(biāo)準(zhǔn)化上面的代碼,您可以創(chuàng)建一個處理該特定屬性注入的 bean。
您可以使用注釋來指定注入,方法是創(chuàng)建注釋以及AnnotatedRequestArgumentBinder. 類似于以下內(nèi)容:
public class Temp implements AnnotatedRequestArgumentBinder<YourAnnotation, Long> {
@Override
public Class<YourAnnotation> getAnnotationType() {
return YourAnnotation.class;
}
@Override
public BindingResult<Long> bind(ArgumentConversionContext<Long> context, HttpRequest<?> source) {
if (source.getAttributes().contains(OncePerRequestHttpServerFilter.getKey(SecurityFilter.class))) {
final Optional<Authentication> authentication = source.getUserPrincipal(Authentication.class);
if (authentication.isPresent()) {
return () -> (Long)((JSONObject)authentication.getAttributes().get("account")).get("id");
}
}
return ArgumentBinder.BindingResult.EMPTY;
}
}
添加回答
舉報