[rest api 프로젝트 구축] - spring security (5) 스프링 시큐리티 OAuth 2 설정: 인증 서버 설정

geun kim·2023년 3월 27일
0

REST API 구축

목록 보기
15/20
post-thumbnail

-Granty Type: 토큰 받아오는 방법
-Oauth Grant Type: Password 타입 및 여러 종류가 존재

-password type : 서비스 오너가 만든 클라이언트에서 사용하는 Grant Type, 즉 서비스에서 계정 정보를 가지고 있을때 사용

토큰 발행 테스트

● POST /oauth/token

○ HTTP Basic 인증 헤더 (클라이언트 아이디 + 클라이언트 시크릿)
○ 요청 매개변수 (MultiValueMap<String, String>)

■ grant_type: password
■ username
■ password

○ 응답에 access_token 나오는지 확인

의존성 추가

		<!-- spring security oauth2.0 추가 -->
		<dependency>
			<groupId>org.springframework.security.oauth.boot</groupId>
			<artifactId>spring-security-oauth2-autoconfigure</artifactId>
			<version>2.1.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<version>${spring-security.version}</version>
			<scope>test</scope>
		</dependency>

AuthorizationServer 설정
ClientDetailsServiceConfigurer clients 구성을 inmemory 화 되어 있는데 다른구성은 어떻게
되는지 확인 필요

@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired
AuthenticationManager authenticationManager;

@Autowired
PasswordEncoder passwordEncoder;

@Autowired
AccountService accountService;

@Autowired
TokenStore tokenStore;

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    //비밀번호 인코딩 시 PasswordEncoder를 주입
    security.passwordEncoder(passwordEncoder);
}

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    //테스트 이므로 inmemory db를 사용 , 나중에 적절한 db화가 필요
    clients.inMemory().withClient("myApp") // client id 설정
            .authorizedGrantTypes("password" , "refresh_token") // 허용 할 Grant type 설정
            .scopes("read","write") //
            .secret(passwordEncoder.encode("pass")) //client secret 설정
            .accessTokenValiditySeconds(10*60) //acess token 유효시간 설정
            .refreshTokenValiditySeconds(60*60); //refresh token 유효시간 설정
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints.authenticationManager(authenticationManager) //인증정보를 가지고 있는 authentication manager 설정
            .userDetailsService(accountService) //userDetailsService 설정
            .tokenStore(tokenStore); // tokenStore 설정
}

}


> oauth 서버 테스트

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class AuthServerConfigTest {
@Autowired
AccountService accountService;

@Autowired
MockMvc mockMvc;

@Test
@TestDescription("인증 토큰을 발급 받는 테스트 (인증토큰 받는 가져오는 방식 : password type)")
public void getAuthToken() throws Exception {
    /**
     * 인증토큰 받는 가져오는 방식 : password type
    **/

    String username = "oauth@email.com";
    String password = "oauth";
    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
    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")
            )
            .andExpect(status().isOk())
            .andDo(print())
            .andExpect(jsonPath("access_token").exists());

}

}


> 응답 전문

{
"access_token": "f5ee6845-8132-4e62-906b-010a6169d68e",
"token_type": "bearer",
"refresh_token": "adf851a9-0b9c-4125-be2d-b46b5b59395a",
"expires_in": 599,
"scope": "read write"
}


> postman 설정
![](https://velog.velcdn.com/images/kkaddus/post/fa73147f-c02b-4c28-9f26-cda57d4f21b0/image.png)

![](https://velog.velcdn.com/images/kkaddus/post/a9cd1037-ea5a-4fd5-87a4-8a1dd4a9f285/image.png)
profile
Devops Load Map

0개의 댓글