9

I want to send the username and password to the server using Base64 encoding.

I found that I can import the following module using npm:

    npm install --save angular-base64

I have verified that following folder is created in my project foler: node_modules\angular-base64

In my component.js file I tried to use any of the following line to import the component:

    import 'angular-base64/angular-base64'; 

It does not complain about the importing but when I try to use following line:

    headers.append('Authorization', 'Basic ' + base64.encode('username:temppass'));

It says "Can not find base64".

4
  • if you do this because of security, you fail. When dealing with secrets use https (TLS, SSL a.s.o) Commented Aug 27, 2017 at 10:55
  • @stefanbachert still we need to send the password encrypted because the server side code requires it. Commented Aug 27, 2017 at 11:39
  • With the angular-base64 library, be sure to prefix with a dollar-sign, $, i.e. $base64.encode('username:temppass'). Commented Aug 27, 2017 at 21:14
  • 1
    Possible duplicate of base 64 encode and decode a string in angular (2+) Commented Jan 9, 2018 at 2:28

1 Answer 1

35

You don't really need an external library for that purpose.

The WindowOrWorkerGlobalScope.btoa() method creates a base-64 encoded ASCII string from a String object in which each character in the string is treated as a byte of binary data.

Use the btoa() function to encode:

console.log(btoa("username:temppass")); // dXNlcm5hbWU6dGVtcHBhc3M=

To decode, you can use the atob() function:

console.log(atob("dXNlcm5hbWU6dGVtcHBhc3M=")); // username:temppass

See the list of supported browser here

Sign up to request clarification or add additional context in comments.

3 Comments

btoa() can not be used to encode characters outside of the Latin1 range.
@Shadoweb Buffer.from(<string>).toString('base64') shall be used instead of btoa() now
Thanks @StephanKulla, but in the end it was only VSC complaining wrongly, and a restart solved the issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.