Search code examples
javarestbase64jax-rsrestlet

Restlet how to decode secret in HTTP basic authentication


I have the following class handling one of my routes:

public class HotelsSrv extends ServerResource implements 
   HotelsListResource {
   private String hotelId;

   @Override
   protected void doInit() throws ResourceException {
       super.doInit();
       String str;
       String secret = getRequest().getChallengeResponse().getSecret().toString();
       byte[] bytes = new BASE64Decoder().decodeBuffer(secret)
       str = new String(bytes);

       System.out.println("user: "+getRequest().getChallengeResponse().getIdentifier());

       System.out.println("password: "+str);
}

I am trying to decode the secret so I can verify it using custom procedure but this line raises unknown exception:

    byte[] bytes = new BASE64Decoder().decodeBuffer(secret)

Solution

  • try this code

    public void authenticate(HttpServletRequest req) {
        String authhead = req.getHeader("Authorization");
    
            if (authhead != null) {
                // *****Decode the authorisation String*****
                byte[] e = Base64.decode(authhead.substring(6));
                String usernpass = new String(e);
                // *****Split the username from the password*****
                String user = usernpass.substring(0, usernpass.indexOf(":"));
                String password = usernpass.substring(usernpass.indexOf(":") + 1);
                // check username and password
            }
    }