Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 7f0e1a0c

Přidáno uživatelem Jiri Trefil před téměř 2 roky(ů)

#10425 Zachytávání vyjímek (error http requestů) z AUTH appky a následná propagace přes SPADe na klienta.

Zobrazit rozdíly:

pom.xml
104 104
			<artifactId>spring-boot-starter-security</artifactId>
105 105
		</dependency>
106 106

  
107

  
107
		<dependency>
108
			<groupId>org.apache.httpcomponents</groupId>
109
			<artifactId>httpclient</artifactId>
110
		</dependency>
108 111
		<!-- Junit libraries for unit tests-->
109 112
		<dependency>
110 113
			<groupId>org.junit.jupiter</groupId>
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/httpErrorHandler/CustomErrorHandler.java
1
package cz.zcu.fav.kiv.antipatterndetectionapp.v2.httpErrorHandler;
2

  
3
import org.springframework.http.HttpStatus;
4
import org.springframework.http.client.ClientHttpResponse;
5
import org.springframework.util.StreamUtils;
6
import org.springframework.web.client.DefaultResponseErrorHandler;
7
import org.springframework.web.client.HttpClientErrorException;
8

  
9
import java.io.IOException;
10
import java.io.InputStream;
11
import java.nio.charset.StandardCharsets;
12

  
13
/**
14
 * @author Jiri Trefil
15
 * Custom HTTP error handler for RestTemplate class
16
 *
17
 */
18
public class CustomErrorHandler extends DefaultResponseErrorHandler {
19
    /**
20
     *
21
     * Override default custom behavior of Response Handler to be able to read body of error responses
22
     * because default error handle can only parse body of generic errors.
23
     * @param response Http response containing error code
24
     * @throws IOException if file descriptor (socket) is no longer valid in the response
25
     */
26
    @Override
27
    public void handleError(ClientHttpResponse response) throws IOException {
28
        if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
29
            final InputStream inputStream = response.getBody();
30
            byte[] responseBody = inputStream.readAllBytes();
31
            inputStream.close();
32
            //String responseBody = StreamUtils.copyToString(response.getBody(),StandardCharsets.UTF_8);
33
            throw new HttpClientErrorException(response.getStatusCode(),response.getStatusText(),responseBody,StandardCharsets.UTF_8);
34
        } else {
35
            super.handleError(response);
36
        }
37
    }
38

  
39

  
40
}
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/security/JwtAuthenticationFilter.java
2 2

  
3 3
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.httpExceptions.CustomExceptionHandler;
4 4
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.service.OAuthService;
5
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.utils.JSONBuilder;
6
import org.json.simple.JSONObject;
7
import org.json.simple.parser.ParseException;
5 8
import org.springframework.http.*;
6 9
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
7 10
import org.springframework.security.core.Authentication;
......
9 12
import org.springframework.security.core.userdetails.User;
10 13
import org.springframework.security.core.userdetails.UserDetails;
11 14
import org.springframework.stereotype.Component;
15
import org.springframework.web.client.HttpClientErrorException;
12 16
import org.springframework.web.filter.OncePerRequestFilter;
13 17

  
14 18
import javax.servlet.FilterChain;
......
39 43
            response.getOutputStream().println("{\"error\" : \"Some other error related to jwt token!\"}");
40 44
            return;
41 45
        }
42
        System.out.println("<------------------------tady jsem------------------------->");
43 46

  
44 47
        try {
45 48
            String token = authorizationHeader.replace("Bearer ", "");
......
60 63
                response.getOutputStream().println("{\"error\" : \"Token timed out!\"}");
61 64
                return;
62 65
            }*/
63
        } catch (Exception e) {
66
        }
67
        //4xx or 5xx http response from auth application
68
        //basically copies the response from auth app and send it to client
69
        catch (HttpClientErrorException e){
64 70
            SecurityContextHolder.clearContext();
65
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
66
            response.getOutputStream().println("{\"error\" : \"Some other error related to jwt token!\"}");
71
            //read response body
72
            String responseBody = e.getResponseBodyAsString();
73
            response.setStatus(e.getStatusCode().value());
74
            response.getOutputStream().println(responseBody);
67 75
            return;
68 76
        }
69 77

  
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/utils/JSONBuilder.java
1 1
package cz.zcu.fav.kiv.antipatterndetectionapp.v2.utils;
2 2
import org.json.simple.JSONArray;
3 3
import org.json.simple.JSONObject;
4
import org.json.simple.parser.JSONParser;
5
import org.json.simple.parser.ParseException;
4 6

  
5 7
import java.util.ArrayList;
6 8
import java.util.HashMap;
......
59 61
        //some simple data type without any indentation, we can just return it
60 62
        return value;
61 63
    }
64

  
65
    /**
66
     * Transform string json to json object
67
     * @param jsonString json object in string type
68
     * @return JSONObject parsed string
69
     */
70
    public static JSONObject parseJSON(String jsonString) throws ParseException {
71
        if(jsonString == null||jsonString.length()==0) return null;
72
        JSONParser parser = new JSONParser();
73
        JSONObject json = (JSONObject) parser.parse(jsonString);
74
        return json;
75
    }
76

  
77

  
78

  
79

  
62 80
}
src/main/java/cz/zcu/fav/kiv/antipatterndetectionapp/v2/utils/RequestBuilder.java
1 1
package cz.zcu.fav.kiv.antipatterndetectionapp.v2.utils;
2 2

  
3
import cz.zcu.fav.kiv.antipatterndetectionapp.v2.httpErrorHandler.CustomErrorHandler;
4
import org.json.simple.JSONObject;
5
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
6
import org.springframework.web.client.HttpClientErrorException;
7
import org.springframework.web.client.HttpServerErrorException;
8
import org.springframework.web.client.HttpStatusCodeException;
3 9
import org.springframework.web.client.RestTemplate;
4 10

  
5 11
import java.util.HashMap;
......
12 18
import javax.servlet.http.HttpServletRequest;
13 19

  
14 20
public class RequestBuilder {
15

  
16
    //@Value("${auth.realm.authenticate}")
17
    private static String spadeSignature;
18 21
    private static Logger logger = Logger.getLogger(RequestBuilder.class.getName());
19 22

  
20 23

  
21 24

  
22 25
    public static ResponseEntity<String> sendRequestResponse(String url, Map<String, Object> body) {
23 26
        RestTemplate restTemplate = new RestTemplate();
24
        String json = JSONBuilder.buildJSON(body);
27
        restTemplate.setErrorHandler(new CustomErrorHandler());
28
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
25 29

  
30
        String json = JSONBuilder.buildJSON(body);
26 31
        HttpHeaders headers = new HttpHeaders();
27 32
        headers.setContentType(MediaType.APPLICATION_JSON);
28 33
        //headers.set("X-spade-request",spadeSignature);
......
32 37

  
33 38
    public static ResponseEntity<String> sendRequestResponse(String url, String token) {
34 39
        RestTemplate restTemplate = new RestTemplate();
35

  
40
        //custom error handler to handle http response
41
        restTemplate.setErrorHandler(new CustomErrorHandler());
42
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
36 43
        HttpHeaders headers = new HttpHeaders();
37 44

  
38 45
        headers.setContentType(MediaType.APPLICATION_JSON);
......
42 49
        HttpEntity<String> entity = new HttpEntity<>(null, headers);
43 50
        ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);
44 51
        return response;
52

  
45 53
    }
46 54

  
47 55
    public static ResponseEntity<String> sendRequestResponse(String url, String token, boolean get) {
48 56
        RestTemplate restTemplate = new RestTemplate();
49

  
57
        restTemplate.setErrorHandler(new CustomErrorHandler());
58
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
50 59
        HttpHeaders headers = new HttpHeaders();
51 60

  
52 61
        headers.setContentType(MediaType.APPLICATION_JSON);
......
58 67
        return response;
59 68
    }
60 69

  
70

  
71
    public static ResponseEntity<String> sendRequestResponse(String url, Map<String, Object> body, String token) {
72
        RestTemplate restTemplate = new RestTemplate();
73
        restTemplate.setErrorHandler(new CustomErrorHandler());
74
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
75

  
76
        String json = JSONBuilder.buildJSON(body);
77
        HttpHeaders headers = new HttpHeaders();
78
        headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
79

  
80
        headers.setContentType(MediaType.APPLICATION_JSON);
81
        //headers.set("X-spade-request",spadeSignature);
82
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
83
        return restTemplate.postForEntity(url, entity, String.class);
84
    }
85

  
61 86
}

Také k dispozici: Unified diff