gpt4 book ai didi

java - 如何使用 HttpURLConnection 在 Java Web 服务中执行身份验证

转载 作者:行者123 更新时间:2023-11-30 02:27:49 24 4
gpt4 key购买 nike

我已经在 netbeans ide 中创建了这个 Web 服务在客户提出任何请求之前,我想要基本授权。该服务工作正常,但如何使用 httpconnection 类从客户端传递用户名和密码。这是我的网络服务。

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
}

这是我的客户

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;
}
}

最佳答案

客户端的这行代码将添加基本身份验证所需的 header

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

在服务器端,您需要读取“Authorization” header 并提取内容

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];

我还没有测试所有代码,但它应该可以工作

关于java - 如何使用 HttpURLConnection 在 Java Web 服务中执行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184364/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com