Quick Expense Manger. Your free expense manager. Lots of features. The application is also ad free.

Mock Authorization Server in Spring Boot Integration Test

Posted on Aug. 5, 2018
mock-authorization-server-spring-boot-integration-test

Many of my friends were requesting to post an article on mocking Authorization server while doing Integration Test in Spring Boot. In this post I will explain how to use a test profile to mock your Authorization server while accessing protected resources in Integration Test.


When you have many micro services interacting with each other in your application, it sometimes becomes difficult to test one component in isolation from the rest.


Suppose you have an Authorization server that handles user's Authentication and Authorization to protected resources and you are using Oauth 2.0 for this purpose. And you have a different service whose resources are protected by the Authorization server.


So, to access these protected resources using the rest end points, you need to get an access token. But when you are testing your service in isolation, you don't have connection to the Authorization server. But without an access token you would not be able to access your protected resources.


So, you need to mock the Authorization server to get a dummy access token using which you would be able to access your protected resources for your testing.


Here is just a sample of how your test package structure should look like.




Here is the code for the mocked Authorization Server


@Configuration
@EnableAuthorizationServer
@ActiveProfiles("test")
public class AuthorizationTestServer extends AuthorizationServerConfigurerAdapter {

private AuthenticationManager authenticationManager;


@Autowired
public AuthorizationTestServer(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.checkTokenAccess("permitAll()");
oauthServer.allowFormAuthenticationForClients();
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
super.configure(clients);
clients.inMemory()
.withClient("user")
.secret("password")
.authorizedGrantTypes("password")
.scopes("openid");
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
endpoints.authenticationManager(this.authenticationManager);
}
}

As you can see we are using a test profile. Rest of the details are same as actual Spring Authorization with Oauth. If you are new the Spring Security using Oauth 2.0, you can refer to my article Oauth Integration with Spring Security


We also need to mock the User Details Service as our mocked Authorization server is using the authorization grant type as password and it will use the User Details service to verify the credentials.


@Service
@ActiveProfiles("test")
public class UserDetailTestService implements UserDetailsService {

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

return new User("dummyUser","dummyPassword",true,true,
true,true, AuthorityUtils.createAuthorityList("USER"));
}
}

Now we are all set to get a dummy access token to test our end points.


@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@AutoConfigureMockMvc
public class JmStudentServiceApplicationTests {

@Autowired
private WebApplicationContext wac;

@Autowired
private MockMvc mockMvc;


@Autowired
private TestRestTemplate restTemplate;

@Autowired
private StudentRepository studentRepository;

@Test
public void test() throws Exception{

String accessToken = obtainAccessToken("dummyUser", "dummyPassword");
Student student = new Student();
student.setId("2222");
student.setName("test student");

studentRepository.createStudent(student);
assertTrue(studentRepository.getStudentById("2222").getName().equals("test student"));

MvcResult result = mockMvc.perform(get("/students/by-id/2222")
.header("Authorization", "Bearer " + accessToken)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();


String str = result.getResponse().getContentAsString();
assertTrue(str.contains("\"id\":\"2222\""));
}

private String obtainAccessToken(String username, String password) throws Exception {

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("username", username);
params.add("password", password);
params.add("scope", "openid");

String base64ClientCredentials = new String(Base64.encodeBase64("user:password".getBytes()));


ResultActions result
= mockMvc.perform(post("/oauth/token")
.params(params)
.header("Authorization","Basic " + base64ClientCredentials)
.accept("application/json;charset=UTF-8"))
.andExpect(status().isOk());

String resultString = result.andReturn().getResponse().getContentAsString();

JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(resultString).get("access_token").toString();
}

}


As we can see we are using mockMvc to test our rest endpoints. In the method obtainAccessToken, we are calling our mock Authorization server to give us a dummy access token for our dummy user.


And we are using that access token to get our protected resources. If you are wondering about the rest controller end points /students/by-id and the Student Repository, you can check my article on Integration Test with Spring Boot where I have discussed in detail how to Integration test your application using Spring Boot.


Hope this clears all doubts regarding mocking the Authorization server while testing your application. Please leave your queries in the comment section.


Sharing is Caring!

Quick Expense Manger. Your free expense manager. Lots of features. The application is also ad free.

GET FREE UPDATES


RECOMMENDED POSTS FOR YOU


profile image

Kaushik Baruah


ABOUT

My name is Kaushik Baruah and I am the chief blogger on this Blog. I have developed this Blog from scratch using Django as the backend and here I like to share my experience as software engineer and research engineer with my online readers. I will try to focus on career planning, latest emerging technologies and tutorials on various computer science subjects. You can follow me on Twitter, Facebook and Google+

GET FREE UPDATES

POPULAR POSTS

Copyright © 2018
About Us

My name is Kaushik Baruah and I am the chief blogger on this Blog. I have developed this Blog from scratch using Django as the backend and here I like to share my experience as software engineer and research engineer with my online readers. I will try to focus on career planning, latest emerging technologies and tutorials on various computer science subjects.

Get Free Updates