리소스 서버 : 리소스 접근을 관리한다. (일단 이렇게 요약하고 좀 더 자세하게 공부 하자)
permitAll과 anonymous의 차이점 anonymous에 인증이 되면 anonymous 유저는 접근 못함
ResourceServerConfig (리소스 서버 설정)
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("event");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.anonymous()//익명 사용자 허용
.and()
.authorizeRequests()
.mvcMatchers(HttpMethod.GET,"/api/**")
.anonymous() //permitAll과 anonymous의 차이점 anonymous에 인증이 되면 anonymous 유저는 접근 못함
.anyRequest()
.authenticated()//그 밖에 다른 요청은 인증 과정을 거쳐야 함
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler()); //접근 권한이 없을 시 OAuth2AccessDeniedHandler를 사용한다.
}
}
Test class (EventOAuthContollerTest)
/**
* bearer token 리턴
*/
private Object getBearerToken(String username, String password) throws Exception {
return "Bearer "+ getToken(username, password);
}
/**
* oauth 서버 연동
* access token 리턴
*/
private String getToken(String username, String password) throws Exception {
/**
* 인증토큰 받는 가져오는 방식 : password type
**/
Account account = Account.builder()
.email(username)
.password(password)
.roles(Set.of(AccountRole.ADMIN, AccountRole.USER))
.build();
accountService.saveAccount(account);
String clientId = "myApp"; // clent id
String clientSecret = "pass"; // client secret
ResultActions perform = this.mockMvc.perform(post("/oauth/token")
.with(httpBasic(clientId, clientSecret)) //header에 client id , client secret 추가
.param("username", username)
.param("password", password)
.param("grant_type", "password"));
String contentAsString = perform.andReturn().getResponse().getContentAsString();
Jackson2JsonParser parser = new Jackson2JsonParser();
return parser.parseMap(contentAsString).get("access_token").toString();
}
//header 정보에 bearer token 부분 추가
//.header(HttpHeaders.AUTHORIZATION, getBearerToken(username,password)) //access_token 추가
@Test
@TestDescription("정상적으로 동작")
public void creatEvent() throws Exception {
EventDto eventDto = EventDto.builder()
.name("Spring")
.description("REST API Development with Spring")
.beginEnrollmentDateTime(LocalDateTime.of(2018, 11, 23, 14, 21))
.closeEnrollmentDateTime(LocalDateTime.of(2018, 11, 24, 14, 21))
.beginEventDateTime(LocalDateTime.of(2018, 11, 25, 14, 21))
.endEventDateTime(LocalDateTime.of(2018, 11, 26, 14, 21))
.basePrice(100)
.maxPrice(200)
.limitOfEnrollment(100)
.location("강남역 D2 스타텁 팩토리")
.build();
String username = "oauth2@email.com";
String password = "oauth";
mockMvc.perform(post("/api/events")
.header(HttpHeaders.AUTHORIZATION, getBearerToken(username,password)) //access_token 추가
.contentType(MediaType.APPLICATION_JSON_UTF8) // 해당 요청에 JSON 본문을 보내고 있다.
.accept(MediaTypes.HAL_JSON) // accept-header 정의, hal_json을 받고 싶다는 선언
.content(objectMapper.writeValueAsString(eventDto))
)
.andDo(print())
//.andExpect(status().isOk())
.andExpect(status().isCreated())
}