开发者

Get parameter from curl command in REST web serivce

I want to get username and password from curl command in REST web service using Plain Java Class. My j开发者_开发百科ava class is

@GET public Response check(String username,String password) { authenticate..... }

I use Netbean IDE with jersey framework. I created web service in POJO java class. Do anyone know how to get username and password in web service java class? My curl command is like :

curl -u username:password http://localhost:8080/project/resources


If this is building on the code from your question here, then getting the username is a matter of adding a new property to the resource annotated with @Context of type javax.ws.rs.core.SecurityContext (let's call it securityContext). Then you can access the username like this:

String username = securityContext.getUserPrincipal().getName();

The password is not available through this API though. This approach will only work if the user has already been authenticated by the container. To get at the password, the property would need to be of type javax.ws.rs.core.HttpHeaders (let's call it httpHeaders). Using this object, you'd have to call

String authHeader = httpHeaders.getRequestHeader("Authorization").get(0);

Using the curl command you listed would default to using HTTP basic authentication, giving you the username and password in a base64 encoded string consisting of username:password. To get those values you would need to parse, base64 decode, and parse again. The curl command you provided would add the following header to the request:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

In the code snippet I provided before, authHeader would have the value

Basic dXNlcm5hbWU6cGFzc3dvc.mQ=

Getting the username and password would be like so

String[] pair = base64decode(authHeader.split(" ")[1]).split(":");

In that code substitute base64decode with your base64 decoding library of choice. After this call the username would be in pair[0] and the password would be in pair[1]. Note that all of this code is lacking null and boundary checks as well as exception handling that production code would require. It also only supports basic authentication. If you needed to support other authentication methods you would need to handle whatever decoding and parsing that method requires.

It seems to me that JAX-RS is geared more towards using the SecurityContext approach and relying on the container to authenticate the request, so understand all of the caveats with using the HttpHeaders approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜