2 回答

TA贡献1862条经验 获得超7个赞
如果您仍在寻找解决方案,这就是有效的方法。您必须提供一个实现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)
}
}
}
使用构建器添加的所有声明都将添加到Authentication对象中,并且可以在任何控制器中访问,例如:
@Get("/hello-world")
fun hello(authentication: Authentication): String =
authentication["username"] as String
如果您使用的是 Kotlin,还可以在 Authentication 方法上添加扩展方法以获取您添加到 Authentication 类的属性,例如: fun Authentication.username(): String = this.attributes["username"]
注意:username只是一个例子。它可用作name身份验证实例上的实例变量。

TA贡献1872条经验 获得超4个赞
UserDetails 认证后不存在。唯一可用的对象是身份验证。如果您想标准化上面的代码,您可以创建一个处理该特定属性注入的 bean。
您可以使用注释来指定注入,方法是创建注释以及AnnotatedRequestArgumentBinder. 类似于以下内容:
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;
}
}
添加回答
举报