Skip to content
Permalink
Browse files

Fixed OAuth related problems in the integration test

  • Loading branch information...
borabilgin committed Feb 6, 2019
1 parent 5209fce commit 680043a7a745d579aafcbd5fcf0c35e5f7b52431
@@ -26,10 +26,10 @@ public void configure(ResourceServerSecurityConfigurer resources) throws Excepti
@Override
public void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.and()
.authorizeRequests()
.antMatchers("/actuator/**", "/api-docs/**").permitAll()
.antMatchers("/secure/**" ).authenticated();
.requestMatchers()
.and()
.authorizeRequests()
.antMatchers("/actuator/**", "/api-docs/**").permitAll()
.antMatchers("/secure/**" ).authenticated();
}
}
@@ -3,10 +3,12 @@
import com.demo.imagebrowser.domain.User;
import com.demo.imagebrowser.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
@@ -32,4 +34,9 @@ public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException
UserDetails details = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
return details;
}

@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
@@ -1,2 +1,3 @@
spring.datasource.url = jdbc:h2:mem:test
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.H2Dialect
spring.datasource.url=jdbc:h2:mem:test
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
logging.level.org.springframework.security=DEBUG
@@ -5,8 +5,8 @@ security.encoding-strength=9
security.security-realm=ImageBrowser JWT Realm

security.jwt.client-id=jwtclientid
security.jwt.client-secret=S7h5R3dxgg19S
security.jwt.client-secret=$2a$09$9llRm6UdbcgPt7wv4M5W8eA3rC8SeRvILDBwEPV94vbGzmwbXbWUm
security.jwt.grant-type=password
security.jwt.scope-read=read
security.jwt.scope-write=write
security.jwt.resource-ids=jwtresourceid
security.jwt.resource-ids=jwtresourceid
@@ -2,8 +2,8 @@ INSERT INTO APP_ROLE (ID, DESCRIPTION, ROLE_NAME) VALUES (1, 'Regular User', 'US
INSERT INTO APP_ROLE (ID, DESCRIPTION, ROLE_NAME) VALUES (2, 'Admin User', 'ADMIN');

-- Password is 'password'
INSERT INTO APP_USER (ID, USERNAME, PASSWORD) VALUES (1, 'Bora', '$2a$09$5pvrWJ0Bg3ARBzWEp9t1IO6GRASmBqIJf7rPZVJpu0iV8BToIlX9y');
INSERT INTO APP_USER (ID, USERNAME, PASSWORD) VALUES (2, 'Admin', '$2a$09$5pvrWJ0Bg3ARBzWEp9t1IO6GRASmBqIJf7rPZVJpu0iV8BToIlX9y');
INSERT INTO APP_USER (ID, USERNAME, PASSWORD) VALUES (1, 'Bora', '$2a$09$uf3HlfTXYL.FYQbi98Y3oOCSgGg3Pyn98UUS3xIqJPWXtE9/Mp0we');
INSERT INTO APP_USER (ID, USERNAME, PASSWORD) VALUES (2, 'Admin', '$2a$09$uf3HlfTXYL.FYQbi98Y3oOCSgGg3Pyn98UUS3xIqJPWXtE9/Mp0we');

INSERT INTO USER_ROLE(USER_ID, ROLE_ID) VALUES (1,1);
INSERT INTO USER_ROLE(USER_ID, ROLE_ID) VALUES (2,1);
@@ -1,43 +1,38 @@
package com.demo.imagebrowser;

import com.demo.imagebrowser.ImagebrowserApplication;
import com.demo.imagebrowser.domain.Feed;
import com.demo.imagebrowser.domain.FeedCategory;
import com.demo.imagebrowser.repository.FeedCategoryRepository;
import com.demo.imagebrowser.repository.FeedRepository;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import java.util.Arrays;
import java.util.List;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.junit.Assert.*;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,
classes = ImagebrowserApplication.class)
@AutoConfigureMockMvc
@TestPropertySource(
locations = "classpath:application-test.properties")
@TestPropertySource(locations = "classpath:application-test.properties")
public class ImageBrowserApplicationIntegrationTest {

@Autowired
private MockMvc mvc;

@Autowired
@@ -46,6 +41,16 @@
@Autowired
private FeedCategoryRepository feedCategoryRepository;

@Autowired
private WebApplicationContext wac;

@Autowired
private FilterChainProxy springSecurityFilterChain;

@Value("${security.jwt.client-id}")
private String jwtClientId;


@Before
public void setup() {
feedCategoryRepository.deleteAll();
@@ -62,6 +67,32 @@ public void setup() {
feedRepository.save(testFeed1);
feedRepository.save(testFeed2);
feedRepository.save(testFeed3);

this.mvc = MockMvcBuilders.webAppContextSetup(this.wac)
.addFilter(springSecurityFilterChain).build();
}

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

String jwtSecret = "jwtclientsecret";
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "password");
params.add("client_id", jwtClientId);
params.add("username", username);
params.add("password", password);

ResultActions result
= this.mvc.perform(post("/oauth/token")
.params(params)
.with(httpBasic(jwtClientId, jwtSecret))
.accept("application/json;charset=UTF-8"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"));

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

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

@Test
@@ -76,16 +107,24 @@ public void shouldReturnAllFeedItems_whenGetFeeds() throws Exception{

@Test
public void shouldThrowError_whenAddingCategoriesUnauthorized() throws Exception{
mvc.perform(get("/secure/category")
.contentType(MediaType.APPLICATION_JSON))
String categoryName = "test_category";
mvc.perform(put("/secure/category", categoryName)
.contentType(MediaType.APPLICATION_JSON)
.param("categoryName", categoryName))
.andExpect(status().isUnauthorized());
}


@Test
public void shouldReturnAddedCategory_whenAddingCategoriesAuthorized() throws Exception{
mvc.perform(get("/secure/category").with(user("Admin"))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isUnauthorized());
String categoryName = "test_category";
String jwtToken = getToken("Admin", "password");

mvc.perform(put("/secure/category", categoryName)
.header("Authorization", "Bearer " + jwtToken)
.contentType(MediaType.APPLICATION_JSON)
.param("categoryName", categoryName))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value(categoryName));
}
}

This file was deleted.

Oops, something went wrong.

0 comments on commit 680043a

Please sign in to comment.
You can’t perform that action at this time.