views:

101

answers:

1

I'm trying to understand Spring 3.0 authentication.

In the code below, why is user.getRole() set as the GrantedAuthority?

public final UserDetails loadUserByUsername(final String username)
{
    final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    UserAccount user = (UserAccount) memcacheService.get(username);

    if (user == null)
    {
        final Query query = entityManager.createQuery("SELECT u FROM UserAccount u WHERE username = :username");
        query.setParameter(USERNAME, username);

        try
        {
            user = (UserAccount) query.getSingleResult();

            memcacheService.put(username, user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
        }
        catch (NoResultException e)
        {
            return null;
        }
    }

    authorities.add(new GrantedAuthorityImpl(user.getRole()));

    return new EnhancedUser(user.getUsername(), user.getEmail(), user.getDisplayName(), user.getPassword(), user
        .getSalt(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(),
        authorities);
}
+1  A: 

In 3.0 the UserDetails object has to maintain the authorities as a list of GrantedAuthority implementations. If some complex or custom handling of roles is required, application developers are supposed to write their own implementation of GrantedAuthority. But in most cases the authority is simply based on roles defined as String so spring-security out-of-the-box provides a default simple implementation of String role based implementation of GrantedAuthority which is GrantedAuthorityImpl.

I hope this is what you wanted to know bcz the question is a bit unclear.

Gopi