Skip to content

Commit

Permalink
Add some access-control unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
ch4mpy committed Feb 16, 2023
1 parent d5e7fbf commit 95d11bf
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
6 changes: 6 additions & 0 deletions apps/backend-api-springboot3/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-oauth2-test</artifactId>
<version>6.0.12</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.acme.backend.springboot.users.web;

import static org.hamcrest.CoreMatchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;

import com.c4_soft.springaddons.security.oauth2.test.annotations.OpenIdClaims;
import com.c4_soft.springaddons.security.oauth2.test.annotations.WithMockJwtAuth;

@WebMvcTest(controllers = UsersController.class)
class UsersControllerTest {
@Autowired
MockMvc api;

@Test
void givenRequestIsAnonymous_whengetUsersMe_thenUnauthorized() throws Exception {
api.perform(get("/api/users/me")).andExpectAll(status().isUnauthorized());
}

@Test
@WithMockJwtAuth(claims = @OpenIdClaims(sub = "Tonton Pirate"))
void givenUserIsNotGrantedWithAccess_whengetUsersMe_thenForbidden() throws Exception {
// @formatter:off
api.perform(get("/api/users/me"))
// should be forbidden as user does is not granted with "ROLE_ACCESS"
.andExpect(status().isOk());
// @formatter:on
}

@Test
@WithMockJwtAuth(authorities = { "ROLE_ACCESS" }, claims = @OpenIdClaims(sub = "Tonton Pirate"))
void givenUserIsGrantedWithAccess_whengetUsersMe_thenOk() throws Exception {
// @formatter:off
api.perform(get("/api/users/me"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.message", is("Hello Tonton Pirate")));
// @formatter:on
}

}

0 comments on commit 95d11bf

Please sign in to comment.