Henry
Henry

Reputation: 777

Configure Spring Security using EJB

until now, I have been using security-realms to authenticate and authorize users. However, I'd like to switch to the Spring Security framework, preferably not using any other parts of the Spring framework. I managed to set-up a httpBasic in-memory authentication, which works fine.

Now I would like to create a custom UserDetailsService implementing my own authorization. My UserDetailsService-Implementation is a Stateless EJB which I cannot inject in to the SecurityConfig, getting the error What can I do to get this working?

Thank you!

This is my only configuration so far:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {

    public SecurityWebApplicationInitializer() {
        super(SecurityConfig.class);
    }
}

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .httpBasic();        
    }
}

@Stateless
public class UserDetailsImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //No Implementation yet
        return null;
    }
}

EDIT:

I changed my UserDetailsServiceImpl from @Stateless to @Service and Autowired it in SecurityConfig. Additionally, I annotated SecurityConfig with

@Configuration
@ComponentScan(basePackageClasses = {UserDetailsServiceImpl.class})

so that it can find the implementation. However, the problem ist injecting my Stateless Service into the UserDetailsService causing the following error:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [de.tobias.carsharing.security.SecurityService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.ejb.EJB(name=, lookup=, description=, beanName=, beanInterface=class java.lang.Object, mappedName=)}

Upvotes: 0

Views: 765

Answers (1)

Đuro
Đuro

Reputation: 61

What's the error you are getting?

You can change annotation on UserDetailsImpl from @Stateless to @Service (package: org.springframework.stereotype.Service) and you can inject it in SecurityConfig with @Autowired private UserDetailsImpl userDetailsImpl and finally register it in your AuthenticationManagerBuilder with auth.userDetailsService(userDetailsImpl).

In case you don't want to use @Autowired injection for some reason, you could manually create new instance of UserDetailsImpl

Upvotes: 1

Related Questions