Spring Security: how to get an authorized user in applicationContext.xml
Sorry for my english. How to get an authorized user in applicationContext.xml
Authentication
class:
public class Authentication {
public Account getAccount(){
return (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}
And in file applicationContext.xml:
<bean id="Authentication" class="com.otv.util.Authentication">
</bean>
<bean id="CurrentAccount"
factory-bean="Authentication"
factory-method="getAccount"/>
But it is not working:
Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'Principal' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public com.otv.model.entity.Account com.otv.util.Authentication.getAccount()] threw exception; nested exception is java.lang.NullPointerException]]
How can I get an authorized user in applicationContext.xml?
UPDATED
If I use as said holmis83. I get error:
org.hibernate.TransientObjectException:object references an unsaved transient instance - save the transient instance before flushing: com.otv.model.entity.Account
In applicationContext.xml:
<bean id="Authentication" class="com.otv.util.Authentication"/>
<bean id="CurrentAccount" factory-bean="Authentication" factory-method="getAccount" scope="request">
<aop:scoped-proxy/>
</bean>
<bean id="PostPaginatorDTO" class="com.otv.model.dto.paginator.PostPaginatorDTO" scope="request">
<property name="account" ref="CurrentAccount" />
</bean>
PostBean
class:
@ManagedProperty(value="#{PostPaginatorDTO}")
public PostPaginatorDTO paginatorDTO;
public List<Post> getEntityList() {
entityList=getDao().findByPostPaginatorDTO(getPaginatorDTO());
return entityList;
}
I guess you are trying to create a bean with another scope than default, which is singleton. Use scope
attribute. If you want to use your scoped bean in a singleton bean, you better use a scoped proxy too.
<bean id="CurrentAccount" factory-bean="Authentication" factory-method="getAccount" scope="request">
<aop:scoped-proxy/>
</bean>
There is no authorized user in the security context during startup. Hence you're facing a NullPointerException
.
Remove CurrentAccount
bean and rename Authentication
bean to:
<bean id="CurrentAccount" class="com.otv.util.Authentication">
</bean>
Now you can wire CurrentAccount
bean into you services and retrieve authorized user during runtime:
currentAccount.getAccount()
I strongly recommend to rename com.otv.util.Authentication
to com.otv.util.CurrentAccount
in order to not mess with org.springframework.security.core.Authentication
.