waffel’s Weblog

Juli 27, 2017

calling NTLMv2 protected ASPX webservice with Spring Boot

Filed under: java,spring — Thomas Wabner @ 9:06 am

What a challenge. I tried to call a REST webservice from a ASPX website with my springboot application. The REST service only supports POST requests (I do not understand why, but this is maybe another story).

When I use the default spring RestTemplate to invoke a REST request I always get error 404 or 401 from the REST service. Doing the same with Chrome or IE the request works without any problem. So what is the difference?

It seems our browsers doing more than the spring RestTemplate. They are doing some roundtrips to handle NTLM authentication. The question is now: How can I do the same with spring?

The answer is fairly simple but I do not have found any official documentation about this. Simple do something like the following:

RestTemplate template = new RestTemplate();
// !!! We require this request to work with NTLMv2

The headForHeaders() method do the NTLMv2 authentication stuff. Any further requests using then the Ntlm auth header to talk with the ASPX service and they can then authenticate and invoke the requests.

For sure, you need general able to authenticate to the service. So check first with your browser if the requests really working for your windows user.


Februar 27, 2013

testing REST interface with Spring 3.2 and a session scoped bean

Filed under: java,spring — Thomas Wabner @ 8:00 pm
Tags: , , , , , , , , ,

There are some nice articles around the „spring 3.2 testing capabilities“ like the spring documentation itself, this blog and this blog.

I wanted to not only test one request/response action against my REST interface. I wanted to simulate and test more of a conversation as it typical happens in the UI.

Following REST interface I wanted to create and test:

public interface RESTCustomer {

method = RequestMethod.POST)
Customer create(@RequestParam("firstname") final String firstname,
@RequestParam("lastname") final String lastname);

method = RequestMethod.DELETE)
void delete(@RequestParam("id") final String... customerIds);

produces = MediaType.APPLICATION_JSON_VALUE,
method = RequestMethod.GET)
Collection<Customer> getAll();

value = "/update",
method = RequestMethod.POST)
Customer update(@RequestParam("id") final String id, @RequestParam("firstname") final String firstname);


Following test steps I had in mind, to test the create method:

  1. Get a list of all customers and remember the count
  2. Create a new customer
  3. Check, that the ID of the returning Customer was updated
  4. Get again a list of all customers
  5. Check the size of the customer list before and after creation … they should differ between one entry/li>

The new Spring Framework version 3.2 introduced some nice feature to do REST testing with minimal effort.

To test such conversion, you need beside the WebApplicationContext a MockHttpSession which has to be used between different mockMvc calls, on one test case.

The following base test structure is required:

  classes = {
public class RESTCustomerTest {
  private WebApplicationContext wac;

  MockHttpSession session;

  MockMvc mockMvc;

  ObjectMapper jsonObjectMapper;

  public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    jsonObjectMapper = new ObjectMapper();

  public void testCreate() throws Exception {

Let assume, there is an implementation of the RESTCustomer service interface like this:

public class CustomerResource implements RESTCustomer {

  private final PlatformService service;

  public CustomerResource(final PlatformService service) {
    this.service = service;

  public Customer create(final String firstname, final String lastname) {
    return service.createCustomer(firstname, lastname);

  public Collection<Customer> getAll() {
    return service.getAllCustomers();


Assume also, that the autowired PlatformService is a Session scoped bean (somewhere configured inside the spring configuration).

Now our testing method can be like this:

  int countCustomers() throws Exception {
    final MvcResult mvcResult = mockMvc.perform(get("/customer").session(session).accept(MediaType.APPLICATION_JSON))
    final Collection<Customer> customers = getRawObjects(mvcResult);
    return customers.size();

Collection<Customer> getRawObjects(final MvcResult mvcResult) throws Exception {
    return jsonObjectMapper.readValue(mvcResult.getResponse().getContentAsString(),
        new TypeReference<Collection<Customer>() {

Customer getRawObject(final MvcResult mvcResult) throws Exception {
    return jsonObjectMapper.readValue(mvcResult.getResponse().getContentAsString(),
        new TypeReference<Customer>() {

  public void testCreate() throws Exception {
    // get default customer list and count
    final int originalCustomerSize = countCustomers();

    // create new customer
    final MvcResult mvcResult = mockMvc
            post("/customer/?firstname={firstname}&lastname={lastname}","testFirstname", "testLastName").session(session).accept(
    final Customer customerObject = getRawObject(mvcResult);
    assertNotNull("id of new customer should not empty", customerObject.get("id"));
    assertEquals("newly firstname should match", "testFirstname", customerObject.get("firstname");

    // again get list of all customers and check, if one more is available
    assertEquals("after new customer was created, the size should be one more", originalCustomerSize + 1, countCustomers());

To get such conversation to work, you need to pass the session with .session(session) between the mockMvc calls. Else, every new mockMvc call creates a new session and your test fail.

REMEMBER: The trick is to pass the autowired MockHttpSession between the mock MVC requests.

April 27, 2009

How to test spring session or request scope beans

Filed under: spring — Thomas Wabner @ 1:45 pm
Tags: , , , , , , , ,

Update Newer Spring Framework versions (I guess starting with 3.1) have better support and a better solution for this problem.

Often you need test cases where you want to use spring configured beans from a existing spring configuration instead of writing mock objects.

In such cases you can use the spring ContextConfiguration class annotation to load your spring configurations. For test cases you may also extend the AbstractTestNGSpringContextTests which gives you nice test support facilities.

But how to test beans which using special scopes like session or request?

The AbstractTestNGSpringContextTests does not provide support to test scoped beans.

Our test module provides a SimpleMapScope implementation, which can be used for scoped beans. There is also a spring configuration for the scopes request and session: session-request-testscopes.xml which can be used as a ContextConfiguration location.

For example you can write follow simple test case:


@ContextConfiguration(locations = {"/org/waffel/test/session-request-testscopes.xml", 
public class SimpleScopeBeansTest extends AbstractTestNGSpringContextTests {

   * A bean which is in scope session.
  private MyBean sessionScopedBean;
  public void testAccessToBean() {


This test uses the test scope spring configuration and another spring configuration, where the sessionScopedBean is in scope session. With the autowired feature, you have instantly access to the bean. Also if the bean is in session or request scope.

The SimpleMapScope implementation:

package org.waffel.test.spring;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

 * This simple scope implementation uses internal a {@link Map} to hold objects
 * in the scope. This scope implementation can be used for testing beans which
 * wants to be stayed for example in session or request scope.
 * <p>
 * To use this scope in your test cases, simple configure a
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} with
 * the required scope name:
 * <pre>
 * &lt;bean class=&quot;org.springframework.beans.factory.config.CustomScopeConfigurer&quot;&gt;
 *   &lt;property name=&quot;scopes&quot;&gt; 
 *     &lt;map&gt; 
 *       &lt;entry key=&quot;session&quot;&gt; 
 *         &lt;bean class=&quot;org.waffel.spring.SessionScope&quot; /&gt; 
 *       &lt;/entry&gt; 
 *     &lt;/map&gt;
 *   &lt;/property&gt; 
 * &lt;/bean&gt;
 * </pre>
 * Because the
 * {@link org.springframework.beans.factory.config.CustomScopeConfigurer} is a
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} all
 * requested beans for the scope loaded with that post processor if the
 * registered scope match.
 * </p>
 * @author waffel
public class SimpleMapScope implements Scope {

   * This map contains for each bean name or ID the created object. The objects
   * are created with a spring object factory.
  private final Map<string , Object> objectMap = new HashMap</string><string , Object>();

   * {@inheritDoc}
  public Object get(final String theName, final ObjectFactory theObjectFactory) {
    Object object = objectMap.get(theName);
    if (null == object) {
      object = theObjectFactory.getObject();
      objectMap.put(theName, object);
    return object;

   * {@inheritDoc}
  public String getConversationId() {
    return null;

   * {@inheritDoc}
  public void registerDestructionCallback(final String theName, final Runnable theCallback) {
    // nothing to do ... this is optional and not required

   * {@inheritDoc}
  public Object remove(final String theName) {
    return objectMap.remove(theName);


The session-request-testscopes.xml source:

< ?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

  <bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <entry key="session">
          <bean class="org.waffel.test.spring.SimpleMapScope" />
        <entry key="request">
          <bean class="org.waffel.test.spring.SimpleMapScope" />


Another approach can be found in ahöhma’s weblog.

Bloggen auf WordPress.com.