简体   繁体   中英

How to perform authentication in a java web service using HttpURLConnection

I have created this webservice in netbeans ide I would like basic Authorization before client make any request. The service works fine but how do I Pass username and password from client using httpconnection class. Here is my webservice.

import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

@WebService(serviceName = "SampleWs")
public class SampleWs implements CreateCustomer {
    @Resource
    WebServiceContext wsctx;
    @Override
    public String createCustomer(Customers customer) {
        String resp="Access Denied";

        MessageContext mctx = wsctx.getMessageContext();

        Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
        String username = (String) http_headers.get("username");//should come from the client request
        String password = (String) http_headers.get("password");//should come from the client request
        if(username.equals("admin")&&password.equals("pass"))
        {
            resp="Authenticated";
        }
       return resp;

    }


}
//interface 
import javax.jws.WebMethod;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

@WebService
@SOAPBinding(style = Style.RPC)
public interface CreateCustomer {
    @WebMethod    String createCustomer(Customers customer);
}
//model class
public class Customers {    
    private int id;
    private String fname;
    private String sname;
    private String gender;
    private String email;

     //getters and setters
} 

And here is my client

public class SampleClient {

    private static final String url_ = "http://localhost:7001/SampleWs/SampleWs";



    public static String testAuthorisation() {
        String varresp = "";
        StringBuilder answer = new StringBuilder();
        try {
            String req = getSoapRequestXMl();
            String name = "adm";
            String password = "pass";

            String authString = name + ":" + password;

            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());//apache lib for Base64
            String authStringEnc = new String(authEncBytes);

            URL url = new URL(url_);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Content-Type", "text/xml");
            //conn.setRequestProperty ("Authorization", "Basic " + authStringEnc);

            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(req);
            writer.flush();

            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                answer.append(line);
            }
            writer.close();
            reader.close();
            varresp = answer.toString();

        } catch (Exception e) {
            e.printStackTrace();
            varresp = "!" + e;

        } finally {
            return varresp;
        }

    }

    private static String getSoapRequestXMl() {
        String request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                + "    <soap:Header/>\n"
                + "    <soap:Body>\n"
                + "        <ns1:hello xmlns:ns1=\"http://ws.ecs.co/\">\n"
                + "            <name>\n"
                + "                <email>testemail@yahoo.com</email>\n"
                + "                <fname>Firsname</fname>\n"
                + "                <gender>Male</gender>\n"
                + "                <id>23</id>\n"
                + "                <sname>Nemuga</sname>\n"
                + "            </name>\n"
                + "        </ns1:hello>\n"
                + "    </soap:Body>\n"
                + "</soap:Envelope>";

        return request;
    }
}

This line of your code in client side will add the required header for Basic authentication

conn.setRequestProperty ("Authorization", "Basic " + authStringEnc);

In server side, you need to read the "Authorization" header and extract the content

Map<String, List<String>> headers= (Map<String, List<String>>) messageContext
                .get(MessageContext.HTTP_REQUEST_HEADERS);

//The header "Basic base64(user:password)
String authHeader = headers.get("Authorization").get(0);

//Remove "Basic "
String authtoken = authorizationHeader.split(" ")[1];

//Decode base64 and read username and password 
String token = new String(DatatypeConverter.parseBase64Binary(authtoken));
String tokenS[] = token.split(":");
String username = tokenS [0];
String password = tokenS [1];

I have not tested all the code, but it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM