Skip to content

Commit 19fa388

Browse files
Add. Authorization to get user by username API
1 parent fc11ea1 commit 19fa388

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

db-data-file.mv.db

0 Bytes
Binary file not shown.

src/main/java/com/springsecuritybasics/security/SecurityConfig.java

+1
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity, Handle
3636
authorize.requestMatchers(antMatcher("/h2-console/**")).permitAll()
3737
.requestMatchers(mvcRequestMatcher.pattern("/signup")).permitAll()
3838
.requestMatchers(mvcRequestMatcher.pattern("/users")).hasRole("admin")
39+
.requestMatchers(mvcRequestMatcher.pattern("/users/{username}")).hasAnyRole("admin", "user")
3940
.anyRequest().authenticated()
4041
).httpBasic(Customizer.withDefaults());
4142

src/test/java/com/springsecuritybasics/controllers/UserControllerTest.java

+24-1
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ void shouldBeAbleToReturnUserByUsername() throws Exception {
181181
SecurityMockMvcRequestPostProcessors
182182
.user(signupRequest.username())
183183
.password(signupRequest.password())
184+
.roles(signupRequest.role())
184185
)
185186
);
186187

@@ -201,7 +202,7 @@ void shouldBeAbleToReturnUserByUsername() throws Exception {
201202
}
202203

203204
@Test
204-
void shouldNotBeAbleToReturnUserByUsernameForUnauthorisedUsers() throws Exception {
205+
void shouldNotBeAbleToReturnUserByUsernameForUnauthenticatedUsers() throws Exception {
205206
ResultActions result = mockMvc.perform(
206207
MockMvcRequestBuilders
207208
.get("/users/{username}", signupRequest.username())
@@ -215,6 +216,27 @@ void shouldNotBeAbleToReturnUserByUsernameForUnauthorisedUsers() throws Exceptio
215216
);
216217
}
217218

219+
@Test
220+
void shouldNotBeAbleToReturnUserByUsernameForUnauthorisedUsers() throws Exception {
221+
ResultActions result = mockMvc.perform(
222+
MockMvcRequestBuilders
223+
.get("/users/{username}", signupRequest.username())
224+
.contentType(MediaType.APPLICATION_JSON)
225+
.with(
226+
SecurityMockMvcRequestPostProcessors
227+
.user(signupRequest.username())
228+
.password(signupRequest.password())
229+
.roles("unauthorisedRoleName")
230+
)
231+
);
232+
233+
result.andExpect(
234+
MockMvcResultMatchers
235+
.status()
236+
.isForbidden()
237+
);
238+
}
239+
218240
@Test
219241
void shouldNotBeAbleToReturnUserByAnotherUsername() throws Exception {
220242
ResultActions result = mockMvc.perform(
@@ -225,6 +247,7 @@ void shouldNotBeAbleToReturnUserByAnotherUsername() throws Exception {
225247
SecurityMockMvcRequestPostProcessors
226248
.user(signupRequest.username())
227249
.password(signupRequest.password())
250+
.roles(signupRequest.role())
228251
)
229252
);
230253

0 commit comments

Comments
 (0)