小编EnG*_*oPy的帖子

将 @PreAuthorize("#oauth2.hasScope('internal')") 与 SpringSecurity 5.4.5 一起使用

我仍在学习并尝试了解 Spring 中使用的安全主题。

我正在开发微服务应用程序,在启动时每个服务都连接到 OAuth 服务并获取他的bearer token. 每项服务都有索赔"scope": ["internal"]
当服务相互通信时,每个端点都受到@PreAuthorize注释的保护。

重要的是,目前我将所有项目从 SpringBoot ver.1.5.9 迁移到 2.4.4,因此我花了很多时间来管理迁移使用该启动版本所需的所有依赖项。此时我使用 Spring Security 5.4.5。

当某个服务调用另一个服务时,出现错误:
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method hasScope(java.lang.String) on null context object

我明白的是我没有OAuth2SecurityExpressionMethods实例或者它是有价值的null

下面是完整的堆栈轨迹:

java.lang.IllegalArgumentException: Failed to evaluate expression '#oauth2.hasScope('internal')'
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:33)
at org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice.before(ExpressionBasedPreInvocationAdvice.java:51)
at org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter.vote(PreInvocationAuthorizationAdviceVoter.java:71)
at org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter.vote(PreInvocationAuthorizationAdviceVoter.java:42)
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:60)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.attemptAuthorization(AbstractSecurityInterceptor.java:238)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:208)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:58)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:750)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:692) …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security spring-boot spring-security-oauth2

6
推荐指数
1
解决办法
5088
查看次数