question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

PreAuthorize expression not finding bean reference

See original GitHub issue

I’m receiving this error Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1057E: No bean resolver registered in the context to resolve access to bean 'securityService' when trying to access an existing bean inside a @PreAuthorize annotation. I’ve used this pattern before on REST controllers. Using hasRole works as expected, so I think I have my security setup correctly. I’m curious if this is a known issue or limitation. I’m using Spring Boot 2.7.3 and Java 17.

UPDATE: Here is a sample project that demonstrates this https://github.com/pcalouche/grpc-starter

Thanks for hard work on this library.

// Example bean used in PreAuthorize expression
public class SecurityService {
  public boolean allow(AuthenticatedPrincipal principal) {
    // more complex stuff could be here
    return true;
  }

  public boolean block(AuthenticatedPrincipal principal) {
    // more complex stuff could be here
    return false;
  }
}
// Security configuration
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
  @Bean // registered bean
  public SecurityService securityService() {
    return new SecurityService();
  }

  @Bean
  public InMemoryUserDetailsManager userDetailsService() {
    PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    UserDetails user =
        User.withUsername("user")
            .password(passwordEncoder.encode("password"))
            .roles("ADMIN")
            .build();
    return new InMemoryUserDetailsManager(user);
  }

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic();

    return http.build();
  }

  @Bean
  public AuthenticationManager authenticationManager(
      AuthenticationConfiguration authenticationConfiguration) throws Exception {
    return authenticationConfiguration.getAuthenticationManager();
  }
}
@GRpcService
@Slf4j
public class GreetingService extends GreetingServiceGrpc.GreetingServiceImplBase {
  @PreAuthorize("@securityService.allow(#principal)") // does not work
  //  @PreAuthorize("hasRole('ADMIN')") // works as expected
  public void sayHello(GreetingRequest request, StreamObserver<GreetingResponse> responseObserver) {
    GreetingResponse reply =
        GreetingResponse.newBuilder().setMessage("Acknowledging " + request.getMessage()).build();
    responseObserver.onNext(reply);
    responseObserver.onCompleted();
  }
}
@RestController
@RequestMapping("test")
public class TestController {

  @PreAuthorize("@securityService.block(#principal)") // works as expected
  // @PreAuthorize("hasRole('ADMIN')") // works as expected
  @GetMapping
  public String hello() {
    return "Hello";
  }
}
syntax = "proto3";

package net.energyhub.example.grpc.protos;

option java_multiple_files = true;
option java_package = "net.energyhub.example.grpc.protos";

service GreetingService {
  rpc sayHello(GreetingRequest) returns (GreetingResponse){}
}

message GreetingRequest {
  string message = 1;
}

message GreetingResponse {
  string message = 1;
}

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:10

github_iconTop GitHub Comments

1reaction
jvmletcommented, Oct 6, 2022

Thanks, @pcalouche , I’ll be able to have a look after 14/10 (vacation )

0reactions
jvmletcommented, Dec 5, 2022

4.9.1 was released

Read more comments on GitHub >

github_iconTop Results From Across the Web

Using other bean and method in Spring Security @PreAuthorize
You have to use @ , see Spring Security Reference: Referring to Beans in Web Security Expressions. If you wish to extend the...
Read more >
Spring Security: Delegating authorization checks to bean ...
Delegating access decisions to beans​​ Within security expressions we can reference beans using the @beanname syntax. This feature can help us to ...
Read more >
15. Expression-Based Access Control - Spring
Access Control using @PreAuthorize and @PostAuthorize. The most obviously useful annotation is @PreAuthorize which decides whether a method can actually be ...
Read more >
Intro to Spring Security Expressions - Baeldung
These expressions are responsible for defining the access control or authorization to specific URLs and methods in our application: @Bean ...
Read more >
Spring – PreAuthorize doesn't work - iTecNote
I'm writing a socket server (no web-application !) application and want to use method-based ... <security:expression-handler ref="expressionHandler" ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found