Anton Nakonechnyi
Anton Nakonechnyi

Reputation: 796

Spring Security principal cannot be found from SpEL

I want to get data from CrudRepository for RestResource by a JPA Query:

public interface IContactRepository extends PagingAndSortingRepository<Contact, Long> {

    @Query("select contact from Contact contact where contact.owner.login = ?#{principal.username}")
    @RestResource( path = "my")
    List<Contact> findByOwner();
}

But I get this:

Property or field 'principal' cannot be found on object of type 'java.lang.Object[]' - maybe not public?

I can get principal directly:

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

but I need it inside the interface to get direct access to RestResource.

Upvotes: 3

Views: 2577

Answers (1)

RichardMZ
RichardMZ

Reputation: 120

I was facing the same problem and I fixed it by doing:

provide a bean of type SecurityEvaluationContextExtension

as the documentation said.

Below are Java and XML configurations from the doc:

Java Configuration

@Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
    return new SecurityEvaluationContextExtension();
}

XML Configuration

<bean class="org.springframework.security.data.repository.query.SecurityEvaluationContextExtension"/>

Hope this helps :)

Upvotes: 9

Related Questions