I have defined the endpoint and given the username and password for the authorization under named credentials (Spring 15 Feature),when I do a http Request I am getting Unauthorized(401)

HttpRequest req = new HttpRequest();
Http http = new Http();
HTTPResponse res = http.send(req);

Response : 401

But if I hardcode the end point,username and password in the request, I am authorised (without using named credentials)

HttpRequest req = new HttpRequest();
// Specify the required user name and password to access the endpoint
// As well as the header and header information
String username = 'myname';
String password = 'mypwd';

Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' +
req.setHeader('Authorization', authorizationHeader);

// Create a new http object to send the request object
// A response object is generated as a result of the request  

Http http = new Http();
HTTPResponse res = http.send(req);

Response : OK

Is that Named credential includes the Authorization Header automatically?

What am I missing here ?

  • Did you enable the named credentials for the profile? Jan 23, 2015 at 11:58
  • Yes I have done it
    – Pavan
    Jan 23, 2015 at 12:15
  • Did you ever figure this out? I too can auth if I use apex to define the header value, but I always get 401 Unauthorized with the Named Credential.
    – Doug Ayers
    Feb 10, 2015 at 23:01
  • Nope! I still haven't found a proper solution.
    – Pavan
    Feb 21, 2015 at 14:53

2 Answers 2


I am having the same problem with named credentials, and I think I have figured out what's going on. I used Runscope to inspect the headers which are being sent with the HTTP callout.

It turns out that the value of the "Authorization" header is not being prefixed with the word "Basic". For example, if your username is "abc" and your password is "123", using named credentials sends this in the header:

Authorization: YWJjOjEyMw==

Instead, it should be sending this for it to work:

Authorization: Basic YWJjOjEyMw==

For now, it seems that hard-coding the "Authorization" header is the way to go. (You could store the username and password in a custom setting to keep it out of your code.)

  • 1
    Yes you are right ! The auth header is missing ,but then If I store the the username and password in the custom settings it would be visible to all the org users(Not in a managed Package) ,The purpose of named credentials is to simplify the authentication ,If I store the username and password in custom settings then the only use named credentials is to maintain the endpoint.
    – Pavan
    Feb 21, 2015 at 14:57

You need to check Generate Authorization Header check box on Named Credential.

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .