1+ package com .asquera .elasticsearch .plugins .http ;
2+
3+ import org .elasticsearch .http .*;
4+ import org .elasticsearch .common .settings .Settings ;
5+ import org .elasticsearch .env .Environment ;
6+ import org .elasticsearch .node .service .NodeService ;
7+ import org .elasticsearch .rest .RestController ;
8+ import org .elasticsearch .common .inject .Inject ;
9+ import org .elasticsearch .common .Base64 ;
10+
11+ import org .elasticsearch .rest .StringRestResponse ;
12+
13+ import static org .elasticsearch .rest .RestStatus .*;
14+
15+ import java .io .IOException ;
16+
17+ public class HttpBasicServer extends HttpServer {
18+ private final String user ;
19+ private final String password ;
20+
21+ @ Inject public HttpBasicServer (Settings settings , Environment environment , HttpServerTransport transport ,
22+ RestController restController ,
23+ NodeService nodeService ) {
24+ super (settings , environment , transport , restController , nodeService );
25+
26+ this .user = settings .get ("http.basic.user" );
27+ this .password = settings .get ("http.basic.password" );
28+ }
29+
30+ public void internalDispatchRequest (final HttpRequest request , final HttpChannel channel ) {
31+ if (authBasic (request )) {
32+ super .internalDispatchRequest (request , channel );
33+ } else {
34+ channel .sendResponse (new StringRestResponse (FORBIDDEN ));
35+ }
36+ }
37+
38+ private boolean authBasic (final HttpRequest request ){
39+ String authHeader = request .header ("Authorization" );
40+
41+ if (authHeader == null ) {
42+ return false ;
43+ }
44+
45+ String [] split = authHeader .split (" " );
46+ String decoded = null ;
47+
48+ try {
49+ decoded = new String (Base64 .decode (split [1 ]));
50+ } catch (IOException e ) {
51+ logger .warn ("Decoding of basic auth failed." );
52+ return false ;
53+ }
54+
55+ String [] user_and_password = decoded .split (":" );
56+ String given_user = user_and_password [0 ];
57+ String given_pass = user_and_password [1 ];
58+
59+ if (this .user .equals (given_user ) &&
60+ this .password .equals (given_pass )) {
61+ return true ;
62+ } else {
63+ return false ;
64+ }
65+ }
66+ }
0 commit comments