Jax-rs Basic Authentication using HeaderParam

@Path("/v1/docs")
@Consumes({ MediaType.APPLICATION_JSON })
@Named
@Api(value = "/v1/docs", description = "Docs Service" )
public interface DocumentService {

    @POST
    @Path("/{caseId}/{emailMessageid}")
    @PermitAll
    @ApiOperation(value = "Docs Service",
            notes = "Create Salesforce Account, Contact"
    )
    @ApiResponses(value = {
            @ApiResponse(code = 500, message = "Unexpected failure")
    })
    void uploadAndDeleteDocumentFromSalesforceAndUpdateCase(@PathParam("caseId") String caseId, 
                                                            @PathParam("emailMessageid") String emailMessageid,  
                                                            @HeaderParam("authorization") String authentication);
}
@Named
public class DocumentServiceImpl implements DocumentService {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(DocumentServiceImpl.class);

    @Value("${SF_DOCS_USERNAME}")
    private String sfDocsUsername;

    @Value("${SF_DOCS_PASSWORD}")
    private String sfDocsPassword;

    @Override
    public synchronized void uploadAndDeleteDocumentFromSalesforceAndUpdateCase(String caseId, String emailMessageId, String authentication) {
        if(isUserAuthenticated(authentication)){
          
        } else {
            logger.error("caseId {} emailId {} authentication failed {}", caseId, emailMessageId, authentication);
        }
    }

    public boolean isUserAuthenticated(String authString){
        if (authString!=null){
            String[] authParts = authString.split("\\s+");
            String authInfo = authParts[1];
            byte[] bytes  =  DatatypeConverter.parseBase64Binary(authInfo);
            String decodedAuth = new String(bytes);
            String[] userNameAndPassword = decodedAuth.split(":");
            if (userNameAndPassword[0].equals(sfDocsUsername) && userNameAndPassword[1].equals(sfDocsPassword)){
                return true;
            } else
                logger.info("isUserAuthenticated did not match decodedAuth {} username {}", decodedAuth, sfDocsUsername+":"+sfDocsPassword);
        }
        return false;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s