Skip to content

Commit 2ee0a8a

Browse files
tschimanslavisa-baeldung
authored andcommitted
BAEL-684 Adding spring JPA to resource servers
1 parent 5f0f26e commit 2ee0a8a

18 files changed

Lines changed: 487 additions & 133 deletions

File tree

‎spring-cloud/spring-cloud-bootstrap/gateway/src/test/java/com/baeldung/spring/cloud/bootstrap/gateway/GatewayApplicationLiveTest.java‎

Lines changed: 0 additions & 69 deletions
This file was deleted.
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
package com.baeldung.spring.cloud.bootstrap.gateway;
2+
3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4+
import org.apache.http.entity.ContentType;
5+
import org.junit.Assert;
6+
import org.junit.Test;
7+
import org.springframework.boot.test.web.client.TestRestTemplate;
8+
import org.springframework.http.*;
9+
import org.springframework.util.LinkedMultiValueMap;
10+
import org.springframework.util.MultiValueMap;
11+
12+
public class IntegrationTest {
13+
14+
private TestRestTemplate testRestTemplate = new TestRestTemplate();
15+
private String testUrl = "http://localhost:8080";
16+
17+
@Test
18+
public void testAccess() throws Exception {
19+
ResponseEntity<String> response = testRestTemplate.getForEntity(testUrl + "/book-service/books", String.class);
20+
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
21+
Assert.assertNotNull(response.getBody());
22+
23+
//try the protected resource and confirm the redirect to login
24+
response = testRestTemplate.getForEntity(testUrl + "/book-service/books/1", String.class);
25+
Assert.assertEquals(HttpStatus.FOUND, response.getStatusCode());
26+
Assert.assertEquals("http://localhost:8080/login", response.getHeaders().get("Location").get(0));
27+
28+
//login as user/password
29+
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
30+
form.add("username", "user");
31+
form.add("password", "password");
32+
response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class);
33+
34+
//extract the session from the cookie and propagate it to the next request
35+
String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0];
36+
HttpHeaders headers = new HttpHeaders();
37+
headers.add("Cookie", sessionCookie);
38+
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
39+
40+
addBook();
41+
42+
//request the protected resource
43+
response = testRestTemplate.exchange(testUrl + "/book-service/books/1", HttpMethod.GET, httpEntity, String.class);
44+
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
45+
Assert.assertNotNull(response.getBody());
46+
47+
addRatings();
48+
49+
//request the admin protected resource to determine it is still protected
50+
response = testRestTemplate.exchange(testUrl + "/rating-service/ratings", HttpMethod.GET, httpEntity, String.class);
51+
Assert.assertEquals(HttpStatus.FORBIDDEN, response.getStatusCode());
52+
53+
//login as the admin
54+
form.clear();
55+
form.add("username", "admin");
56+
form.add("password", "admin");
57+
response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class);
58+
59+
//extract the session from the cookie and propagate it to the next request
60+
sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0];
61+
headers = new HttpHeaders();
62+
headers.add("Cookie", sessionCookie);
63+
httpEntity = new HttpEntity<>(headers);
64+
65+
//request the protected resource
66+
response = testRestTemplate.exchange(testUrl + "/rating-service/ratings", HttpMethod.GET, httpEntity, String.class);
67+
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
68+
Assert.assertNotNull(response.getBody());
69+
70+
//request the discovery resources as the admin
71+
response = testRestTemplate.exchange(testUrl + "/discovery", HttpMethod.GET, httpEntity, String.class);
72+
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
73+
}
74+
75+
private void addRatings() {
76+
//login as user/password
77+
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
78+
form.add("username", "user");
79+
form.add("password", "password");
80+
ResponseEntity<String> response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class);
81+
82+
//extract the session from the cookie and propagate it to the next request
83+
String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0];
84+
HttpHeaders headers = new HttpHeaders();
85+
headers.add("Cookie", sessionCookie);
86+
headers.add("ContentType", ContentType.APPLICATION_JSON.getMimeType());
87+
Rating rating = new Rating(1L, 4);
88+
89+
HttpEntity<Rating> httpEntity = new HttpEntity<>(rating, headers);
90+
91+
//request the protected resource
92+
ResponseEntity<Rating> bookResponse = testRestTemplate.postForEntity(testUrl + "/rating-service/ratings", httpEntity, Rating.class);
93+
Assert.assertEquals(HttpStatus.OK, bookResponse.getStatusCode());
94+
Assert.assertEquals(rating.getBookId(), bookResponse.getBody().getBookId());
95+
Assert.assertEquals(rating.getStars(), bookResponse.getBody().getStars());
96+
}
97+
98+
private void addBook(){
99+
//login as user/password
100+
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
101+
form.add("username", "admin");
102+
form.add("password", "admin");
103+
ResponseEntity<String> response = testRestTemplate.postForEntity(testUrl + "/login", form, String.class);
104+
105+
//extract the session from the cookie and propagate it to the next request
106+
String sessionCookie = response.getHeaders().get("Set-Cookie").get(0).split(";")[0];
107+
HttpHeaders headers = new HttpHeaders();
108+
headers.add("Cookie", sessionCookie);
109+
headers.add("ContentType", ContentType.APPLICATION_JSON.getMimeType());
110+
Book book = new Book("Baeldung", "How to spring cloud");
111+
112+
HttpEntity<Book> httpEntity = new HttpEntity<>(book, headers);
113+
114+
//request the protected resource
115+
ResponseEntity<Book> bookResponse = testRestTemplate.postForEntity(testUrl + "/book-service/books", httpEntity, Book.class);
116+
Assert.assertEquals(HttpStatus.OK, bookResponse.getStatusCode());
117+
Assert.assertEquals(book.getAuthor(), bookResponse.getBody().getAuthor());
118+
Assert.assertEquals(book.getTitle(), bookResponse.getBody().getTitle());
119+
}
120+
121+
@JsonIgnoreProperties(ignoreUnknown = true)
122+
public static class Book {
123+
124+
private Long id;
125+
private String author;
126+
private String title;
127+
128+
public Book() {
129+
}
130+
131+
public Book(String author, String title) {
132+
this.author = author;
133+
this.title = title;
134+
}
135+
136+
public String getAuthor() {
137+
return author;
138+
}
139+
140+
public void setAuthor(String author) {
141+
this.author = author;
142+
}
143+
144+
public String getTitle() {
145+
return title;
146+
}
147+
148+
public void setTitle(String title) {
149+
this.title = title;
150+
}
151+
152+
public Long getId() {
153+
return id;
154+
}
155+
156+
public void setId(Long id) {
157+
this.id = id;
158+
}
159+
}
160+
161+
@JsonIgnoreProperties(ignoreUnknown = true)
162+
public static class Rating {
163+
private Long id;
164+
private Long bookId;
165+
private int stars;
166+
167+
public Rating() {
168+
}
169+
170+
public Rating(Long bookId, int stars) {
171+
this.bookId = bookId;
172+
this.stars = stars;
173+
}
174+
175+
public Long getId() {
176+
return id;
177+
}
178+
179+
public void setId(Long id) {
180+
this.id = id;
181+
}
182+
183+
public Long getBookId() {
184+
return bookId;
185+
}
186+
187+
public void setBookId(Long bookId) {
188+
this.bookId = bookId;
189+
}
190+
191+
public int getStars() {
192+
return stars;
193+
}
194+
195+
public void setStars(int stars) {
196+
this.stars = stars;
197+
}
198+
}
199+
200+
201+
}

‎spring-cloud/spring-cloud-bootstrap/svc-book/pom.xml‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,17 @@
4242
<artifactId>spring-boot-starter-data-redis</artifactId>
4343
</dependency>
4444

45+
<dependency>
46+
<groupId>org.springframework.boot</groupId>
47+
<artifactId>spring-boot-starter-data-jpa</artifactId>
48+
</dependency>
49+
50+
<dependency>
51+
<groupId>com.h2database</groupId>
52+
<artifactId>h2</artifactId>
53+
<scope>runtime</scope>
54+
</dependency>
55+
4556
<dependency>
4657
<groupId>org.springframework.boot</groupId>
4758
<artifactId>spring-boot-starter-test</artifactId>

‎spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/BookServiceApplication.java‎

Lines changed: 0 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,35 +3,11 @@
33
import org.springframework.boot.SpringApplication;
44
import org.springframework.boot.autoconfigure.SpringBootApplication;
55
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
6-
import org.springframework.web.bind.annotation.GetMapping;
7-
import org.springframework.web.bind.annotation.PathVariable;
8-
import org.springframework.web.bind.annotation.RequestMapping;
9-
import org.springframework.web.bind.annotation.RestController;
10-
11-
import java.util.Arrays;
12-
import java.util.List;
136

147
@SpringBootApplication
158
@EnableEurekaClient
16-
@RestController
17-
@RequestMapping("/books")
189
public class BookServiceApplication {
1910
public static void main(String[] args) {
2011
SpringApplication.run(BookServiceApplication.class, args);
2112
}
22-
23-
private List<Book> bookList = Arrays.asList(
24-
new Book(1L, "Baeldung goes to the market", "Tim Schimandle"),
25-
new Book(2L, "Baeldung goes to the park", "Slavisa")
26-
);
27-
28-
@GetMapping("")
29-
public List<Book> findAllBooks() {
30-
return bookList;
31-
}
32-
33-
@GetMapping("/{bookId}")
34-
public Book findBook(@PathVariable Long bookId) {
35-
return bookList.stream().filter(b -> b.getId().equals(bookId)).findFirst().orElse(null);
36-
}
3713
}

‎spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/SecurityConfig.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import org.springframework.beans.factory.annotation.Autowired;
44
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.http.HttpMethod;
56
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
67
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
78
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@@ -22,8 +23,11 @@ protected void configure(HttpSecurity http) throws Exception {
2223
http.httpBasic()
2324
.disable()
2425
.authorizeRequests()
25-
.antMatchers("/books").permitAll()
26-
.antMatchers("/books/*").hasAnyRole("USER", "ADMIN")
26+
.antMatchers(HttpMethod.GET, "/books").permitAll()
27+
.antMatchers(HttpMethod.GET, "/books/*").permitAll()
28+
.antMatchers(HttpMethod.POST, "/books").hasRole("ADMIN")
29+
.antMatchers(HttpMethod.PATCH, "/books/*").hasRole("ADMIN")
30+
.antMatchers(HttpMethod.DELETE, "/books/*").hasRole("ADMIN")
2731
.anyRequest().authenticated()
2832
.and()
2933
.csrf()

spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/Book.java renamed to spring-cloud/spring-cloud-bootstrap/svc-book/src/main/java/com/baeldung/spring/cloud/bootstrap/svcbook/book/Book.java

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,21 @@
1-
package com.baeldung.spring.cloud.bootstrap.svcbook;
1+
package com.baeldung.spring.cloud.bootstrap.svcbook.book;
22

3+
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
4+
5+
import javax.persistence.Entity;
6+
import javax.persistence.GeneratedValue;
7+
import javax.persistence.GenerationType;
8+
import javax.persistence.Id;
9+
10+
@Entity
11+
@JsonIgnoreProperties(ignoreUnknown = true)
312
public class Book {
13+
@Id
14+
@GeneratedValue(strategy = GenerationType.AUTO)
415
private Long id;
516
private String author;
617
private String title;
718

8-
public Book(Long id, String title, String author) {
9-
this.id = id;
10-
this.author = author;
11-
this.title = title;
12-
}
13-
1419
public Book() {
1520
}
1621

0 commit comments

Comments
 (0)