BeanCreationException during acceptance tests - spring

I use Spring Security to authentication.
I modified my annotation #Page which define which type of user is able to access page.
After that in my acceptance tests i started to get errors in:
public void login(#Named("email") String email, #Named("password") String password) {
fillUpLoginForm(email, password);
waitForElement(MosquitoElements.MainNavigationBar.LOGOUT);
securityService.login(email, password); // authenticates user in test environment too
}
i found that there's something wrong here:
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(email, password);
getSecurityContext().setAuthentication(authenticationManager.authenticate(token));
What can cause problem?
Error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.securityContext': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
Change in annotation:
before
boolean requiresAdminPrivileges() default false;
after
Authorities[] requiredAuthorities();
In appliaction everything works fine, only tests have probles.

Try to emulate sesseion scope in your test's application context:
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="session">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>

Related

Scoped proxy tag not taking effect - configuration error?

I've inherited a bit of a monster system. It is a Spring framework server meant to run on Weblogic.
The code as it stands seems to work perfectly for another developer. I can clean, compile and package the project without error. However, when I try to deploy the generate .war file to my Weblogic server, I get the following error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.com.example.portal.uil.delegate.ExceptionLogDelegate': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
This error points me to the following bean, which is in an external library:
<bean id="com.externalLibrary.ExceptionLogDelegate" class="com.externalLibrary.ExceptionLogDelegate" scope="session">
<aop:scoped-proxy />
<property name="errorLogBuffer" ref="com.externalLibrary.ErrorLogDao" />
</bean>
After searching around for that error for a while, it seems that it is most often experienced when the aop:scope-proxy tag is omitted. This bean is being loaded as such:
<bean id="exceptionResolver" class="foo.mypackage.SoapFaultDetailExceptionResolver">
<property name="marshaller" ref="marshaller"/>
<property name="exceptionLogDelegate" ref="foo.mypackage.ExceptionLogDelegate"/>
</bean>
The strange thing is that with no files changed, this exact code works fine on my colleague's machine, so I assume I'm missing some magic configuration step.
Could anyone perhaps point me at thing to look for?
Kind Regards

Expression in service activator doesn't execute (Spring Integration)

I debug my app and the expression doesn't execute.
<bean id="remover" class="org.example.Remover"/>
<bean id="key" class="java.lang.String">
<constructor-arg value="KEY"/>
</bean>
<integration:service-activator input-channel="middleChannel"
expression="#remover.remove(key)"/>
No Exception. method doesn't call.
That’s not true: there must be an exception. You don’t show the whole flow to determine the part who swallows your exception on the matter.
Your expression is like:
#remover.remove(key)
You correctly call remover bean, but there is no such a property like key in the Message object - just only headers and payload. That’s why I’m making a conclusion that you have problems.
You can turn on debug logs for the Spring Integration category and follow you the trace of the call.

how to handle name not found exception in application-context.xml?

I am creating a spring project using Oracle and jboss server.
I have one bean in my application-context.xml.
<!-- Datasource for TaskManager -->
<jee:jndi-lookup id="tmTestDataSource"
jndi-name="test_datasource" expectedtype="javax.sql.DataSource"/>
<bean id="tmTestJdbcTemplate" name="TmTestJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="tmTestDataSource" />
</bean>
If the 'test_datasource' JNDI (one datasource.xml file in jboss deployment folder, which contains db credentials like url, uid, password) inside the file found deployment is successfull, but if the file is not there then the deployment is failing.
I want to handle this exception so that deployment should not fail.
how I can do this. Can anybody provide me any solution.
Thanks.
Instead of using dataSource args constructor, you can set it using setter method.
This way your bean will be created but its datasource will be null. So you will get NPE if you try to use it, but at least bean creation tree will not be stalled.

Test Web Service Client with spring MockWebServiceServer

I am currently trying to test my web service clients with spring MockWebServiceServer as the real web service servers are not exposed yet. I have been following the spring doc http://docs.spring.io/spring-ws/site/reference/html/client.html but still getting some issue like below:
org.springframework.ws.client.WebServiceIOException: I/O error: Connection refused: connect; nested exception is java.net.ConnectException: Connection refused: connect
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:545)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:386)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:380)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:372)
I believe the error has something to do with the WebServiceTemplate I autowired into my WS client as below. Since I am using a MockWebServiceServer, I do not think a real HTTP connection is needed, but why it is complaining as such? Do I still need to start up my tomcat server to make the localhost:8080 accessible even using the MockWebServiceServer?
<bean id="vehicleOrderConfirmationWebServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory"/>
<property name="marshaller" ref="vehicleOrderConfirmationMarshaller" />
<property name="unmarshaller" ref="vehicleOrderConfirmationMarshaller" />
<property name="defaultUri" value="http://localhost:8080"/>
</bean>
Anyone could suggest?
the mocked server does not need a real http connection. it mocks the MessageSender.
how did you create you mocked web server ? below usage must be enough a real mocked server
MockWebServiceServer.createServer(vehicleOrderConfirmationWebServiceTemplate);
If your client class extends the WebServiceGatewaySupport like the example given by the Spring reference documentation, make sure you have set the WebServiceTemplate by using the inherited setWebServiceTemplate() method.
#Autowired
public CustomerClient (WebServiceTemplate customerClientWebServiceTemplate) {
setWebServiceTemplate(customerClientWebServiceTemplate);
}

Accessing HttpServletRequest during DaoAuthenticationProvider authenticate in Spring Security

I need to access the HttpServletRequest object from within my DaoAuthenticationProvider in Spring security.
The security component extends the DaoAuthenticationProvider and we override the authenticate method to perform some custom authentication / validation. The additional check is required to validate user's ip-address which comes in the request url as a query string parameter (Ex: http://domain.com/context?ip=192.168.0.1).
The current approach I am trying is to make use of RequestContextHolder thread-local and get the http request in my custom DAOAuthenticationProvider.
Some other solutions that I read here and on spring forums seems to suggest to inject AuthenticationDetailsSource, use of custom-filter and other steps which I don't understand due to being new to spring security.
We would have different web applications which use the same security component to perform authentication.
Can someone please point me in a correct direction or help me with any approaches implemented previously ?
You can use RequestContextHolder and it effectively contains the same request, though Spring Security will usually wrap the incoming request, so you may get a different reference depending on whether you place the RequestContextFilter before or after the Spring Security chain (note that you could easily check this yourself by comparing the value returned from RequestContextHolder with the request in an application controller).
It is also relatively easy to inject a custom AuthenticationDetails as you mentioned:
package com.mycompany;
public class MyWebAuthenticationDetailsSource implements AuthenticationDetailsSource {
public Object buildDetails(Object context) {
return ((HttpServletRequest)context).getParameter("ip");
}
}
Then use
<bean id="ads" class="com.mycompany.MyWebAuthenticationDetailsSource />
<bean id="formLoginFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
<property name="authenticationDetailsSource" ref="ads" />
<property name="authenticationManager" ref="authenticationmanager" />
</bean>
and add this as a custom filter as described in the reference manual. In 3.1 the namespace supports this directly in the form-login element. Authentication.getDetails() will then return the value of your "ip" parameter.
Note that you probably shouldn't be using 3.0.4, as it has known security vulnerabilities.
Also, can you explain how the "ip" parameter is being set?
You can add Spring's RequestContextFilter in your web.xml. This way, attributes will be saved on current thread on every request. Then, you can get original HtttpServletRequest:
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
HttpServletRequest request = attributes.getRequest();

Resources