开发者

Spring Security Role Prefix and Custom User Details Service

How do I set the role prefix to "" with a custom user details service in Spring?

    <beans:bean id="authService" class="com.cisco.badges.business.services.AuthenticationService"/>

<authentication-manager>
        <authentication-provider user-service-ref="authService">
            <password-encoder ref="passwordEncoder">
                <salt-source ref="saltSource" />
            </password-encoder>
        </authentication-provider>
    </authentication-manager>

@Service("authService")
public class AuthenticationService extends BaseService implements UserDetailsService, IAuthenticationService {

    @Autowired
    IUserRepository userRepository;

    @Autowired
    IAuthorityRepository authorityRepository;

    public AuthenticationService() {

    }

    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {

        User user = userRepository.findByUsername(username);

        if(user == null)
            throw new UsernameNotFoundException("No user with username '" + username + "' found!");

        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();

       开发者_如何学JAVA for (Role role : user.getRoles()) {
            authList.add(new GrantedAuthorityImpl(role.getName()));
        }

        UserAuthentication userAuthentication = new UserAuthentication(user.getUsername(), user.getPassword(), user.getEnabled() == 0 ? false : true, true, true, true, authList);

        userAuthentication.setSalt(user.getSalt());
        userAuthentication.setId(user.getId());

        return (UserDetails)userAuthentication;
    }
}


<beans:bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter">
    <beans:property name="rolePrefix" value="" />
</beans:bean>

just like this


It's also possible to append a _ROLE to your current roles using a mapper. In Spring Boot:

@Bean
public GrantedAuthoritiesMapper grantedAuthoritiesMapper() {
    SimpleAuthorityMapper simpleMapper = new SimpleAuthorityMapper();
    simpleMapper.setPrefix("ROLE_");

    return simpleMapper;
}

After that you should add this mapper to your provider:

@Bean
public DaoAuthenticationProvider authenticationProvider() {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
    provider.setAuthoritiesMapper(authoritiesMapper());

    return provider;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜