반응형

공부하면서 만든 Oauth Server에 대한 테스트를 Postman으로는 했는데 실제로 Client Code가 필요하게 되었다. 


2017/09/04 - [Development/Java] - [Spring Boot]Oauth server 적용해보기


테스트만 할 경우에는 Postman만 써도 상관이 없지만 실제 Client 가 호출을 하려면 code가 필요하다. 그래서 여기저기 구글링을 해가면서 찾아봤다. 


우선 Oauth Token을 발급 받기위한 코드가 필요하다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public String getOAuth2Token(String username, String password) {
        final String CLIENT_ID = "myclient";
        final String CLIENT_SECRET = "secret";
        final String GRANT_TYPE = "password";
        final String SERVER_URL = "http://localhost:" + port;
        final String API_OAUTH_TOKEN = "/oauth/token";
 
        String clientCredentials = CLIENT_ID + ":" + CLIENT_SECRET;
        String base64ClientCredentials = new String(Base64.encodeBase64(clientCredentials.getBytes()));
 
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("Authorization""Basic " + base64ClientCredentials);
 
        MultiValueMap<StringString> parameters = new LinkedMultiValueMap<>();
        parameters.add("grant_type", GRANT_TYPE);
        parameters.add("username", username);
        parameters.add("password", password);
 
        HttpEntity<MultiValueMap<StringString>> request = new HttpEntity<>(parameters, headers);
 
        @SuppressWarnings("rawtypes")
        ResponseEntity<Map> response;
 
        URI uri = URI.create(SERVER_URL + API_OAUTH_TOKEN);
        response = restTemplate.postForEntity(uri, request, Map.class);
        return  (String) response.getBody().get("access_token");
    }
cs


위에 작성된 메소드를 보면 파라메터로 id, password를 받게 되어있다. 이건 실제 사용자의 id, password를 넣으면 된다. 그리고 그 이외에 필요한 정보들은 final 상수로 정의를 해놓았다. 다만 Testcase로 작성 하다 보니 port 는 Random하게 들어간다. 호출 형태는 Postman에서 작성했던 것을 그대로 Code로 옮긴걸로 생가하면 된다.  저렇게 호출을 하게되면 결과값으로 access_token값을 받게된다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void getOAuth2TokenTest(){
    Assert.assertNotNull(accessToken);
}
 
@Test
public void getTestWithAccessToken(){
    final String SERVER_URL = "http://localhost:" + port;
    final String API_URL = "/private?access_token={access_token}";
 
    ResponseEntity<String> responseEntity = restTemplate.getForEntity(
            SERVER_URL + API_URL,
            String.class,
            accessToken);
 
    Assert.assertEquals("private", responseEntity.getBody());
}
cs


이렇게 받은 access_token을 실제 API 에 넣어서 보내주면 전에 글에서 postman  으로 실행했던 것과 동일한 결과를 얻을 수 있다.

위에 작성된 소스 코드는 https://github.com/blusky10/study_spring 에 가서 OauthServiceTest.java파일을 보면 확인 할 수 있다.


728x90
반응형
반응형

Oauth 2.0 에 대해서 공부를 하다가 용어에 대한 명확한 이해가 필요해서 정리를 했다.


Access Token : 보호된 리소스에 일정 기간동안 접근할 수 있는 권한을 가진 문자열

- Scope : Token 소유자가 접근할수 있는 보호된 리소스 셋


Client : Resource를 이용하려고 하는 Web 이나 App. 

Resource Sever : 실제 정보를 가지고 있는 대상. 

Resource Owner : Resource 에 대한 소유자.


Access Token 을 얻는 절차는 아래처럼 설명할 수 있다.


Resource Owner 

 Client

 Resource Server

 1. Client 에게 정보 요청


 

 

 2. Resource Server 에 있는 Resource Owner의 정보를 접근 할수 있는 권한 요청

 

3. Resource Server 에 로그인

(Client 에서 Resource 서버에 로그인할수 있는 페이지를 바로 연결해줌)

 


 4. Resource Server에 있는 Resource Owner의 특정 정보에 Client가 접근하는것을 허용하는지 여부 확인 (Yes/No)

 

 

 

 

 5. Resource Owner 가 Client의 접근을 허용할 경우 Client 에게 Code를 보냄

 

 6. Code를 받아서 Client_id, secret를 code와 함께 Resource Server로 보냄

 
  

 7. Client가 보낸 client_id, secret, code를 확인한 후 access tockent을 발급

 

 8. 발급받은 access token으로 Resource Server 에 있는 owner 의 정보에 접근.

 


위 표에서 설명한 것은 Access Token을 얻는 방법중 한가지에 대해서 설명한 것이다. 꼭 이것과 동일하지 않을 수 있다. 그렇지만 저런 한가지 흐름을 알아 두면 다른것을 이해하기에 도움이 될거라 생각이 된다. 


728x90
반응형
반응형

Redis ERR Client sent AUTH, but no password is set


이런 에러가 나올때가 있다.  


Request for authentication in a password-protected Redis server. Redis can be instructed to require a password before allowing clients to execute commands. This is done using the requirepass directive in the configuration file.

If password matches the password in the configuration file, the server replies with the OK status code and starts accepting commands. Otherwise, an error is returned and the clients needs to try a new password.

Note: because of the high performance nature of Redis, it is possible to try a lot of passwords in parallel in very short time, so make sure to generate a strong and very long password so that this attack is infeasible.


(출처 : https://redis.io/commands/auth)


내용을 살펴 보자면 Redis는 Client 가 command를 실행하기 위해서 password를 요구할수 있다. 그리고 그 패스워드는 configuration file 에 requirepass로 저장되어 있다. 바로 저 requiredpass가 없을때 위와 같은 에러메세지가 나온다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
$ redis-cli -6379
127.0.0.1:6379> config get requirepass
1"requirepass"
2""
127.0.0.1:6379> config set requirepass mypass
OK
127.0.0.1:6379> config get requirepass
(error) NOAUTH Authentication required.
127.0.0.1:6379> auth mypass
OK
127.0.0.1:6379> config get requirepass
1"requirepass"
2"mypass"
cs


값을 설정하기 위해서는 위와 같은 절차로 진행 하면 된다. 

redis-cli -p 6379 를 통해서 redis 접속후에 config get requirepass 명령어를 실행해본다. requirepass 가 위와 같이 빈값으로 나올 경우 set 명령어를 통해서 requirepass를 설정해준다. 그리고 설정해준 password 에 auth 설정을 해주면 모든 절차는 끝났다. 그리고 다시 실행해보면 에러는 발생하지 않는다. 



728x90
반응형

+ Recent posts