i am trying to include spring security in a web application. For this i wrote my own UserDetailsService implementation which looks like this:
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("userRepositoryImpl")
public class UserRepositoryImpl implements UserDetailsService {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional(readOnly = true)
public User loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = entityManager.find(User.class, username);
if (user == null)
throw new UsernameNotFoundException("Username not found: "
+ username);
return user;
}
}
My problem is that the entityManager always is null when it calls the loadUserByUserName method.
I tried some things suggested here in some similar answers, but nothing helped.
This is my current security-app-context.xml:
<http use-expressions="true" auto-config="true">
<intercept-url pattern="/task/" access="permitAll" />
<intercept-url pattern="/task/**" access="isAuthenticated()" />
<!-- <intercept-url pattern="/**" access="denyAll" /> -->
<form-login />
</http>
<beans:bean id="userRepositoryImpl" class="de.sveri.jeiwomisa.model.UserRepositoryImpl" autowire="byType">
</beans:bean>
<beans:bean id="passwordEncoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder">
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref="userRepositoryImpl">
<password-encoder ref="passwordEncoder" />
</authentication-provider>
</authentication-manager>
Any Ideas what might be wrong there?
Regards,
Sven
Edit: Trying a bit more i found out that i cannot use the entityManager in my generic DaoImpl during the login process.
But i can use it sending and receiving data in another process. This is the Dao:
@Transactional
public abstract class DaoImpl<T> implements Dao<T> {
private Class<T> type;
@PersistenceContext
protected EntityManager em;
public DaoImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
type = (Class) pt.getActualTypeArguments()[0];
}
...
}
I wonder why it is like this. Obviously i dont understand much of how spring works, so it would be great if someone could shed a light.
Thanks to a nice guy from the spring team in the forums i got it working.
I had to change the xml definition and add a tag so that my security-app-context.xml looks like this:
This is the link to the forum entry: http://forum.springsource.org/showthread.php?128626-EntityManager-null-when-implementing-UserDetailsService