questioneverything
questioneverything

Reputation: 11

Spring Security Acquire Roles from a Web Service

Looking to use Spring MVC + Spring Security with annotations. Spring Security has great features for obtaining role information from an XML file or a database. However, our role information is accessible from a custom-built SOAP web service. Any ideas how I can get the role information from the Web Service?

Ideally, I'd like to override hasRoles(), etc and modify it so it would then call the SOAP WS and return back the user's roles. How would I do that?

Or any other ideas?

Upvotes: 1

Views: 264

Answers (1)

nKognito
nKognito

Reputation: 6363

If you need custom attributes while using spring-security you have to implement your own UserDetailsService interface which contains the following method:

public UserDetails loadUserByUsername(final String email)

So after retrieving user from datasource add calls to your roles web-service... Something like that:

public class UserDetailsExtendedService implements UserDetailsService {
    @Autowired
    private UsersDAO usersDao;

    private UserDetails prepare(com.data.User user) {
        boolean enabled = user.getState().equals(UserState.Active);

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (UserRole r: /*CALL TO WEB-SERVICE*/) {
          authorities.add(new GrantedAuthorityImpl(r.getName()));
        }

        return new UserDetails(user.getId(), user.getEmail(), user.getPassword(), user.getNickname(), user.getPosition(), user.getAvatar(), user.getCommunicationLanguage().getCode(), 
            user.getNotificationChannel(), user.getPartnerId(), enabled, enabled, enabled, enabled, authorities);
    }

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(final String email)
            throws UsernameNotFoundException, DataAccessException, HibernateException {
        com.data.User user = usersDao.getByEmail(email);
        if (user == null)
            throw new UsernameNotFoundException(email);

        return prepare(user);
    }
}

Upvotes: 1

Related Questions