Oauth2 서버에서 /oauth/token URL을 통해 토큰을 발급받을 수 있다.
토큰을 발급받기 위해서는 AuthConfig에서 등록한 Client의 id와 secret 키를 헤더에 담고 username, password, grant_type을 입력해서 보내줘야 한다.
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class AuthConfigTest {
@Autowired
private AccountService accountService;
@Autowired
private MockMvc mockMvc;
public Account createAccount(){
return Account.builder()
.name("kimseonjin616")
.password("password")
.roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
.build();
}
@Test
public void getToken() throws Exception {
String clientId = "myapp";
String clientSecret = "pass";
Account account = createAccount();
accountService.create(account);
// Header에 Client id & secret 넣어주고 유저 내용을 넣어준다.
mockMvc.perform(post("/oauth/token")
.with(httpBasic(clientId, clientSecret))
.param("username", account.getUsername())
.param("password", "password")
.param("grant_type", "password")
)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("access_token").exists());
}
}