Express: BasicAuth - javascript

I'm trying to do some basic authorisation to my the endpoints in an express app using express-basic-auth, but it keeps giving me a 401 unauthorised. I think the headers I'm sending in Post man are incorrect:
Middleware:
app.use(basicAuth({
users: {'admin': 'supersecret'},
unauthorizedResponse: 'You are not authorized.'
}));
Postman GET request headers:
Authorization:admin:supersecret
How can I get authorised based on the headers?

Your authorization header should look like this: Authorization: Basic YWRtaW46c3VwZXJzZWNyZXQ=
The last part is the result of encoding admin:supersecret. I just found this tool to generate basic authentication headers, however, Postman can generate the headers itself. Just click on the Authorization option next to Headers and choose Basic Auth.

Related

Post call not placing headers in call. Axios

I'm trying to do an Api Call, this is the code I'm using
axios.get("url", userData, {
headers: {
Authorization: "test"
}
}).then((response) => console.log(response, 'users/me'))
.catch(err => console.log(err))
Its showing me the same error everytime
401 (Unauthorized)
And on the network on chrome dev tools, the Authorization is not appearing at all
Thanks a lot.
The Authorization reqest header has the following general scheme:
Authorization: <auth-scheme> <authorization-parameters>
Let us assume that your user id is john.smith and your password is password (don't do that).
Using the Basic authorization scheme, you take your user ID and password and join them with a colon:
john.smith:password
and then base-64 encyrpt that to get
am9obi5zbWl0aDpwYXNzd29yZA==
The Authorization header you need to pass then is
Authorization: Basic am9obi5zbWl0aDpwYXNzd29yZA==
Different schemes, of course, require different things in the header value.
Your 401 Unauthorized response status should have a WWW-Authenticate response header containing a list of 1 or more challenges telling you what authentication scheme(s) you may use.
Install Postman and fiddle with your API call until you get it working.
You can then export the API call as any of a number of different flavors of client-side code, Node.js - Axios being one of them.

Unable to get referer headers working

I have a proxy set up for a third party service that at the moment looks like this:
app.use('/service', (req, res) => {
let url = `http://www.service.com/endpoint/${config.POSTCODER_KEY}${req.url}`
req.headers['Referer'] = 'my.domain.com'
console.log(req.headers['Referer'])
req.pipe(request(url)).pipe(res)
})
As you can see I am trying to add Referer header to the request and it seems to be working as console.log prints out 'my.domain.com' however request fails and the error I get back from the service is 403 unauthorised referring to Referer header. When I inspect network in inspector tools my referer is displayed as localhost.
I am testing this in Postman api client (https://www.getpostman.com) by setting Referer to my white listed domain and it works. I'm not sure why it uses localhost with express.
Piping streams together only transfers the data in those streams. Headers are not a part of that. When you req.pipe(request(url)) you're only writing the request body to the proxied request. If you want to set the headers used for the proxied request, you have to pass them to request, like:
req.pipe(request({ url: url, headers: req.headers })).pipe(res);
However, as noted in my answer to your previous question, you will also need to properly set the headers on res when the proxied response arrives.

how I send HTTP header with "grant_type=client_credentials"

I am trying to sign up new user on a REST API, and the request should be in this way:
POST /api/oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: Basic YW75cm9pZC12tb28Jp8bGU6c2Vj
grant_type=client_credentials&scope=write
Question 1: the Authorization code is static it must be the same every time I request a new user or I should generate a new base46 code every time?
Question 2: The grant_type.... is a parameter request or a body ( shall I send it with the body or as a parameter)
Very big thanks in advance!
First, from the request code that you provide:
POST /api/oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Authorization: Basic YW75cm9pZC12tb28Jp8bGU6c2Vj
grant_type=client_credentials&scope=write
It seems to me that the request is for acquiring a client (app) access token (using OAuth Client Credentials Grant), rather than a request to sign-up a user. So, I'm basing my answer bellow on this assumption.
Question 1: the Authorization code is static it must be the same every time I request a new user or I should generate a new base46 code every time?
In the case of OAuth Client Credentials Grant, the Authorization header contains the client authentication information (e.g, client_id and client_secret). You usually get this information by registering your client (application) with the API provider.
So the answer is, YES, it should be static as long as the information (the client_id/secret) doesn't change/ expire.
Question 2: The grant_type.... is a parameter request or a body ( shall I send it with the body or as a parameter)
The OAuth spec specifies that grant_type parameter is written in the HTTP request entity-body, so it should be sent in the request body. But, some implementation does allow passing the grant_type parameter in url too.
Question 1: Usually you should use a public token (in this case Basic oauth token) and when this token expires then you should renew it. In the documentation of your api it should exists the time to expire the token and perform a token refresh.
Question 2: Looking your information "grant_type=client_credentials&scope=write" it's a body param request (is a post request with a body)

Angular 2 sending header for authorization

I am trying to get data from API that has oAuth authentication.
What I am doing is sending the auth request from server1 (where my Angular app is) to server2 and I get the access token. Then I put the token in the JS variable and I am trying to access an API endpoint.
My js code looks like this:
let headers = new Headers({ 'Authorization': "Bearer " + oAuthAccessToken });
let options = new RequestOptions({ headers: headers });
let url = "http://example.com/api/getSomething"
this.http.post(url, body, options)
.subscribe( res => {
console.log(res.json())
});
The problem is that I am always getting "401 Unathorized". When I inspect the request in the Network tab of Chrome Dev Tools I see two strange things - first the request method is OPTIONS not POST and the header Authorization is missing.
Any idea what I might be doing wrong ? Why is the header not set ?
Edit:
The problem was that Angular sends OPTIONS request before the POST and my app firewall was expecting Authorization header to be always present. This header is not present in the OPTIONS request so I was getting Unauthorized. I changed my server app to send proper headers on OPTIONS request and now everything is fine.
Thanks for the help.
I think the browser try to discover which http methods are allowed, so the first request is an request with the OPTIONS method. Usually the backend service answers with Access-Control-Allow-Methods inside the header. Afterwards the browser sends the real request.
I think that you need to allow CORS, then it should work as expected
As you are dealing with cross-domain requests, Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. so the option request is just to check is the server support CORS.
From : https://stackoverflow.com/a/21783145/3279156
Content-Type should be like below:
let header= new Headers({'Content-type':'application/x-www-form-urlencode'});
header.append('Authorization',"Bearer " + token);
let opt= new RequestOptions({headers:header});

JWT (JSON Web Token) with PHP and Angular.js

I have an Angular.js application and I am trying to implement authentication to my PHP backend using a JWT.
I have the app setup to set the token on login and send the token with every request if it exits. I was following the information here, though it is for Node.js not PHP: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/.
The information there was extremely helpful, but I do not understand why the token should be in the Authorization header with the text 'Bearer ' before the token. Could I just put the token there without 'Bearer '? Is there a recommended method for where the token should go in the request?
My other issue is where to store the token on the front end. The website recommended using $window.sessionStorage which doesn't seem to work well for my case because it seems to prevent someone from using multiple tabs which isn't very intuitive.
My question really comes down to:
Where do I put the token in the request header?
How should I store the token on the front end?
The use of the Bearer keyword is recommended in the RFC6750 - section Authorization Request Header Field:
Clients SHOULD make authenticated requests with a bearer token using
the "Authorization" request header field with the "Bearer" HTTP
authorization scheme. Resource servers MUST support this method
The libraries I've been working with always require it before the token itself. So the request header should be as follows:
Authorization: Bearer your_token
Regarding the storage I have seen it in $window.sessionStorage too

Categories

Resources