I need to use XML Configuration for some parts of my Spring Security Implementation. All that I am concerned with at the moment is JWT Authorization, the JWT is passed to me. Using Spring Security I determine if the user is authorized access to a REST API endpoint. I can't use Java configuration or the @PreAuthorize annotation.
As an FYI when I was originally using @PreAuthorize or an approach like: .antMatchers("/students/**").access("#oauth2.hasScope('Scope:Admin')");
Everything worked fine. When I was forced to move to XML config and use the security:intercept-url approach, this issue came about.
The error I am getting is:
"message": "Failed to evaluate expression '#oauth2.hasScope('Scope:Admin')'"
The exception is:
java.lang.IllegalArgumentException: Failed to evaluate expression '#oauth2.hasScope('Scope:Admin')'
at org.springframework.security.access.expression.ExpressionUtils.evaluateAsBoolean(ExpressionUtils.java:30) ~[spring-security-core-5.0.3.RELEASE.jar:5.0.3.RELEASE]
... removing exception spew for brevity ...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method hasScope(java.lang.String) on null context object
XML Config:
<!-- only enable this when deving -->
<!-- <security:debug /> -->
<bean id="securityConfig"
class="com.wmay.config.SecurityConfig">
</bean>
<bean id="resourceServerConfig"
class="com.wmay.config.ResourceServerConfig">
</bean>
<bean id="methodSecurityConfig"
class="com.wmay.config.MethodSecurityConfig">
</bean>
<security:http pattern="/**" use-expressions="true" auto-config="true">
<security:intercept-url pattern="/students/**"
access="#oauth2.hasScope('Scope:Admin')"/>
</security:http>
Code Snippets:
@Override
public void configure(HttpSecurity httpSecurity) throws Exception { log.info("Configuring HttpSecurity");
httpSecurity.csrf().disable(); httpSecurity.cors().configurationSource(corsConfigurationSource());
//@// @formatter:off
httpSecurity
.requestMatchers()
.and().authorizeRequests()
.antMatchers("/actuator/**").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
// @formatter:on
}
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
log.info(
"Enabling OAuth2 Method Expression Handler.");
return new OAuth2MethodSecurityExpressionHandler();
}