Encountering a CouchDB 401 Unauthorized Error

I have a couchDB database named "guestbook". Initially, I utilized the following code to add a user to the "_users" database:

$scope.submit = function(){

var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name;
console.log(url);

$http({

    url: url,
    method: "PUT",
    data: {name : $scope.name, 
           password: $scope.pass,
           roles: [],
           type: "user"
          },
    withCredentials: true,
    headers: {"Authorization": auth_hash(adminUsername, adminPass)}
})

.success(function(data, status, headers, config){

    console.log(headers);
    console.log(config);
 });
 }

After successfully adding the user to _users, I used Futon to include that user as a member in the "_security" document of my "guestbook".

Next, when attempting to use the username and password (added as a member to the "guestbook" _security) for retrieving all documents from the "guestbook" database, I encountered an authentication error. Refer to the code below:

   $scope.login = function(){
   var url = "https://sub.iriscouch.com/guestbook/_all_docs";

   $http({
    url: url,
    method: 'GET',
    params: {
        include_docs: true,

    },
    withCredentials: true,
    headers: {"Authorization": auth_hash($scope.uname, $scope.upass)}
})

.success(function(data, status, headers, config){

    $scope.book = data.rows;
    console.log($scope.book);

});
}

function auth_hash(username, password)
{
     return "Basic" +btoa(username + ":" + password);
}

However, whenever trying to access "_all_docs", I consistently receive a 401 unauthorized error. The username used for accessing has been properly added as a member in the _security documents of the guestbook database.

If anyone can assist me in identifying what might be incorrect in my approach, it would be greatly appreciated.

Answer №1

Have you included the user name without the org.couchdb.user prefix in the _security object?

Your code is clear to me, but I cannot spot any obvious mistakes. I suggest testing your API calls with tools like Postman (Chrome App) to determine if the issue is caused by the client or server side.

Answer №2

401 error code indicates that Couch is having trouble logging in your user, rather than simply denying them access to the database.

It's possible there was a copy/paste mistake when writing the code example, specifically with this line:

return "Basic" +btoa(username + ":" + password);

You need to add a space after Basic in order for the hash to be properly included in the returned string:

return "Basic " +btoa(username + ":" + password);

If not corrected, this could result in an incorrect Authorization header.

Although the first block of code seems to be functioning correctly, so it's worth exploring other possibilities.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`When trying to utilize $uibModal.open within karma (AngularJS Factory), an error is encountered as it

My current task involves testing a function that triggers the opening of a $uibmodal. Below is my factory function: confirmationMessage: function (message) { var modalInstance = $uibModal.open({ templateUrl: 'views/templates/utilsTemplates/ ...

Optimal approach for reutilizing Javascript functions

After creating a simple quiz question using jQuery, involving show/hide, addClass, and tracking attempts, I am now considering how to replicate the same code for multiple questions. Would it be best practice to modify all variables in both HTML and jQuery, ...

Transform the given text into components applicable to AngularJS

I have a dynamic dashboard with a JSON object that I populate with HTML elements in text format, like this: var items = [ {"id": "panel1", "description": "<div><a ui-sref='page1'>link a</a></div>"}, {"id": "panel2", "de ...

Dealing with date formatting can be a headache when it comes to different

For my project, I have incorporated angularJS and momentJS to handle the date formatting more efficiently. I am facing two specific scenarios: Retrieving dates from a database and displaying them in the user interface: The response I receive from the s ...

Using MUI ClickAwayListener to automatically close the modal upon clicking in React.Js

In order for the modal to work correctly, it should be visible when the 'More' button is clicked and should close when either the More button or any other part of the screen is clicked (excluding the modal itself). I've attempted different m ...

Why isn't the nested intricate directive being executed?

After watching a tutorial on YouTube by John Lindquist from egghead.io, where he discussed directives as components and containers, I decided to implement a similar structure but with a more dynamic approach. In his example, it looked something like this ...

AngularJS UI-Grid filter with intricate condition

How do I apply a filter to a complex expression mapping like "brand.title"? Here is how I have initialized my fields: $scope.gridOptions2.columnDefs = [ { field: 'code', displayName: "Code" }, { field: 'brand.title', displayN ...

Stunning CRUD tables in AngularJS featuring dynamic jQuery pop-up windows

Hello, I have developed a small CRUD application using AngularJS and encountered a minor issue. The application is functioning correctly overall, but there is a problem: when adding a new record and then attempting to edit it, the pop-up box I created does ...

Modify x and y axes in highcharts for stacked columns

Can anyone assist me in finding charts similar to the one shown below? I am interested in utilizing the stacked column charts provided by the highcharts library. However, I need to modify the presentation of the data values as demonstrated in the image. I ...

The strategy of magnifying and shrinking graphs on Google Finance for better analysis and

I am seeking to understand the logic behind a zoom-able graph similar to the one on Google Finance. I am aware that there are pre-made components available, but I am interested in a simple example that breaks down the underlying logic. ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

Vue: The enigmatic world of ghost properties?

During my project work, I encountered the following code snippet: Main component - <ParameterModal>: <template> <modal-wrapper props="..."> <!-- ... other similar templates are present... --> <template v-else-if="moda ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

What is the most effective way to send URL strings to the server-side click handler in a jQuery loop using $.each method?

As I work with URL values in my client-side script, I aim to generate links that can transmit these URL values back to my server-side click handler upon clicking. The server-side code /logclick logs the timestamp and destination of the click for auditing p ...

Is there a way to implement a @click event on a Vuetify expansion panel?

Whenever I use <a>, the design of the <v-btn> expansion panel breaks. How can I incorporate the click event in this situation? I attempted to utilize filters, watch, and computed, but it didn't work. Here's my code: <v-card xs1 ...

Can you make two elements match each other at random?

Currently, I am working on developing a word guessing game where the displayed image should correspond with the word to be guessed. Unfortunately, I am encountering two major challenges in this process. Firstly, I am unable to get the image to display co ...

Are the elements in the second array the result of squaring each element in the first array? (CODEWARS)

I am currently working on a 6kyu challenge on codewars and I've encountered a frustrating issue that I can't seem to figure out. The task at hand involves comparing two arrays, a and b, to determine if they have the same elements with the same mu ...

Calculating the sum() of a specific attribute in Loopback without the need to iterate through every instance of the object

Within my DummyModel, there are attributes named attOne, attTwo, and attThree. If we want to retrieve all instances of attOne, we can utilize the following query: DummyModel.find({where: {attTwo: 'someValue'}, fields: {attOne: true} }); The ab ...

"Seeking a more flexible JSON parser that allows for greater

I am in need of passing various strings that are formatted as json to a json parser. The issue is that jQuery.parseJSON() and JSON.parse() strictly support only a specific json format: If a malformed JSON string is passed, an exception may be thrown. For ...

Send the user to an Angular route once they have successfully authenticated with Google

I'm facing an issue with redirecting users to an Angular route. Here's the scenario: When I'm on the login page and click on Google login, I get redirected to Google for authentication. After successfully logging in, I want to be redirecte ...