[JAX-RS] 2 ways to get the Basic auth username and password

There are 2 ways at least to get the Basic auth username and password in a JAX-RS web method

1. Using the @HeaderParam("Authorization") annotation
[code language=”java”]
@GET
@Path("/usernamepwd")
public String getUsernamePassword(@HeaderParam("Authorization") String header) {
if (header==null) {
return "header is null";
}
String authorization = header.substring("Basic ".length());
byte[] decodedPass = Base64.getDecoder().decode(authorization);
System.out.println("Decoded pass: " + new String(decodedPass));
return new String(decodedPass);
}
[/code]

and
2. Using the generic @Context HttpHeaders
[code language=”java”]
@GET
@Path("/usernamepwdcontext")
public String getUsernamePassContext(@Context HttpHeaders headers) {
List<String> headerList = headers.getRequestHeader("Authorization");
if (headerList == null) {
return "no header in context";
}
String authorization = headerList.get(0);
authorization = authorization.substring("Basic ".length());
byte[] decodedPass = Base64.getDecoder().decode(authorization);
System.out.println("Decoded pass: " + new String(decodedPass));
return new String(decodedPass);
}
[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *