0

I have a file called security.properties which looks like this:

com.example.test.admins=username,username1,username2

I'd like that file to be read in as a string array. That actually works in one package:

package com.example.test.security

import org.springframework.beans.factory.annotation.Value
import org.springframework.ldap.core.DirContextOperations
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator

class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator {
    @Value('${com.example.test.admins}')
    private String[] admins

    @Override
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(
            DirContextOperations userData, String username) {
        def roles = [new SimpleGrantedAuthority("user")]
        if (username in admins)
            roles.add(new SimpleGrantedAuthority("admin"))
        roles
    }
}

I've checked each import, each is used by something other than importing the file.

In a different package, it ignores the string interpolation:

package com.example.test.controller

// imports excluded for brevity

@Controller
class UserController {
    @Value('${com.example.test.admins}')
    private String[] admins

    public User get() {
        def name = // Name gets put here
        def admin = name in admins
        println admins
        println admin
        return new User(name: name, admin: admin)
    }
}

That yields this output in the console:

[${com.example.test.admins}]
false

The only mention of the file is in security-applicationContext.xml

<context:property-placeholder
     location="classpath:security.properties"
     ignore-resource-not-found="true"
     ignore-unresolvable="true"/>

But, copying that into applicationContext.xml doesn't change anything.

lcarsos
  • 1,231
  • 1
  • 11
  • 8
  • The controller is probably using the servlet application context, not the root context. See this: http://stackoverflow.com/questions/11890544/spring-value-annotation-in-controller-class-not-evaluating-to-value-inside-pro – ataylor Oct 08 '13 at 21:54
  • You are exactly correct. Thanks for the link. I'll post an answer. – lcarsos Oct 08 '13 at 22:10

1 Answers1

1

Thanks to @ataylor for pointing me in the right direction.

Controllers in Spring don't use the same context. So I created a service called UserService:

@Service
class UserService {
    @Value('${com.example.test.admins}')
    private String[] admins

    boolean getUserIsAdmin(String username) {
        username in admins
    }

}

And in the UserController autowired in the service and it works like a charm.

lcarsos
  • 1,231
  • 1
  • 11
  • 8