Proper use of HttpRequestInterceptor and CredentialsProvider when performing preauthentication using HttpClient

I am writing an Android application that consumes some of the REST services that I created. These web services do not issue a standard Apache Basic task / response. Instead, in the server code, I want to interrogate the username and password from the HTTP (S) request and compare it with the database user to make sure that they can run this service.

I use HttpClient for this, and I have credentials stored on the client after the initial login (at least the way I see it working). So this is where I am stuck. Proactive authentication under HttpClient requires the installation of an interceptor as a static member. This is an example of using Apache Components.

    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
        @Override
        public void process( final HttpRequest request, final HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
                    ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    };

, . ? , ? , CredentialsProvider, HttpRequestInterceptor? ?

+3
2

HttpClient .

REST API BASIC-, , , . Twitter, API Twitter, .

+2

Nevermind, , . Apache , "http" HttpHost, . . .

0

Source: https://habr.com/ru/post/1744428/


All Articles