Vapor There are difficulties in interpreting the code and 401 error appears when performing

Viewed 84

I am practicing the vapor server after watching this tutorial at https://github.com/thomashbailey/vapor-auth. As you can see from the code, createUser performs well, but if you try to log in, 401 error pops up and I ask you a question.

I'm sending a server request to postman, how should I send it? enter image description here

Isn't it a code that gives tokens when you log in? I don't know. I'd appreciate it if you let me know.

1 Answers

Well, it seems the server is a demo for the HTTP Basic Authentication Scheme.

You have to create a user first providing a password.

Once this is done, when accessing a protected resource you need to authenticate the request via providing a HTTP "Authorization" header.

This can be done by "preemptively" setting the request header "Authorization" in your request as follows:

Combine user name and password separating it with a colon ":" and base64 encode it. Then set the "Authorization" request header as follows shown in the pseudo code:

Authorization: "Basic" + " " + base64("\(username):\(password)")

Another way is to handle the 401 (not authorised) status code through analysing the "WWW-Authentication" response header, which comes along a 401 when you did not set the "Authorization" header. This is explained in detail in the mentioned RFC.

Note that HTTP clients - including Postman - do aid in setting up the Basic Authorization Scheme. You will find that easily in Postman itself.

Edit

You may now notice, that you have to send the username and password in clear, every time you send a request.

This should ring bells of course. In fact, Basic HTTP Authentication is deprecated due to its vulnerabilities. You should of course use HTTPS, to prevent sending the data in clear over the wire - nonetheless, sending a password with every request should make us gripes.

A more modern and more secure scheme is using a bearer token, for example in OAuth or OIDC.

Related