api test with postman in angular project - postman

I want to test my api for resister which is post type it contain username, email, password, phone number. I really don't know how to test api in postman. It should be authorization type of no-auth. After this I have to validate or test api for login then it generate some key then I have to use this key to test other api's.

i believe to test post api withpostman
first you need to put the route of your api and the type of http in your case POST
then go to header tab and add this header(under key/value):-
Content-Type :application/json
then under body tab select row option and insert valid json as below
{
"username": "Omar Shabro",
"email": "o4#o.com",
"phone": "0599"
}

depends first find if any form of auth is being used in such case you will need to handled the auth before sending requests. check the link bellow it will help you in case of auth
https://www.getpostman.com/docs/helpers

Related

How does one keep a user logged in with Django Rest Framework?

I'm new to Django coming from the Firebase world, where authentication and keeping a user logged in is super easy.
In learning Django (Rest Framework) I came to find out that you can log in a user, get a token and save the token in Cookies to reuse is next time that same user goes into the website. Is this the best way to keep a user logged in?
So far, I can log a user in, get their token and some additional info, but I'm not sure how to prevent this from happening over and over again. I'd like to know how to keep the user logged in.
Also, whenever the user gets back on the browser, do I place a POST request to get their own information (if needed to display on the screen)? Always?
I'm very confused as to how authentication/logging in works.
An usual way to handle this problem is to use Jwt auth.
You will issue a short lived token alongside a long lived refresh token to your consumer.
https://github.com/jpadilla/django-rest-framework-jwt
On your frontend side you can implement an automatic refresh mechanism when the token expire.
Example with React: https://medium.com/#monkov/react-using-axios-interceptor-for-token-refreshing-1477a4d5fc26
On browser side, it's depend. For example with single page app, you can fetch info only one and store them in a store.
For multi page app, you could still use cookie or local storage to persist data.
Each Request is anonymous/new, even after you login.
Why I keep loggedin?
Once you logged in, server usually reuturn a token and save it in your local browser. Next time you send request, you can add the token in your request. Then server will know it is still the same user.
What is token?
There a many kinds of token: session token, jwt, basic token...
Token is a string of your identity, and jwt(JSON Web Tokens) is one of the most popular authentication(CORS) solution. This is how original jwt looks like:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
And this is how actual jwt data looks like:
# HEADER:ALGORITHM
{
"alg": "HS256",
"typ": "JWT"
}
# PAYLOAD:DATA
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
# VERIFY SIGNATURE
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
your-256-bit-secret
)
Where do I keep token
Token is storage in your local cookies. For each request, you can get token from local cookies and add to request head. For example, in React:
import Cookies from "universal-cookie"
localCookies = new Cookies();
...
..
fetch(`/api/logs/:id`, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'JWT ' + localCookies.get('token'),
}
})
...
..

How to POST or PATCH users role and access_level for BIM360 on Postman

I have been successful in creating a new Account User from following this tutorial: https://forge.autodesk.com/en/docs/bim360/v1/reference/http/users-POST/#example, and have used the PATCH method to set their status to active on Postman.
I would like to set their role and access_level but I am having trouble doing so. I have followed the link below to try and perform this function, but it requires the user to already be a BIM 360 Project Admin for it to work.
https://forge.autodesk.com/en/docs/bim360/v1/reference/http/projects-project_id-users-user_id-PATCH/
I also tried following the next link below to add a User to a project, but I am getting errors that I am unsure how to fix.
https://forge.autodesk.com/en/docs/bim360/v1/reference/http/projects-project_id-users-import-POST/
URI: https://developer.api.autodesk.com/hq/v2/accounts/:account_id/projects/:project_id/users/import
Method: PATCH
Authorization: *******************************************
Content-Type: application/json
x-user-id: {{user_id}}
Body:
{
"email": "john.smith#mail.com",
"services": {
"document_management": {
"access_level": "account_admin"
}
},
"company_id": ************************************,
"industry_roles": [
************************************
]
}
(The id for industry_role is IT).
Error:
{
"code": 1004,
"message": "this user doesn't exist."
}
I am unsure how I am getting this error since the User Id used for x-user-id is the same user_id associated with the email given in the request body. Is there a way to fix this or another method I can use?
The x-user-id header is not for specifying the user to import but rather:
x-user-id
string
In a two-legged authentication context, the app has access to all users specified by the administrator in the SaaS integrations UI. By providing this header, the API call will be limited to act on behalf of only the user specified.
Remove this field if that's not what you intended.
Verify the user id and email match each other via /GET users and /GET users:userid.
And be sure to provide either the user's email or the user ID and don't provide them both:
Note that you need to specify either an email, or a user_id. However, you cannot specify both.
See doc here

Manually validate flask-extended-jwt's access token

I have a SPA app that contains an form with an upload file field. I have a rest API whose endpoints are protected via flask-extended-jwt JWT. To authenticate the REST endpoints I use #jwt_required. I want to authenticate the upload request as well.
Because of the client side I can't add an Authorization Bearer header so I thought to add the access token as a hidden field when submitting the form.
What is the best way to manually validate the JWT access token after I read it from the form?
class Upload(Resource):
def post(self):
#TODO: check for access token
access_token = None
if 'access_token' in request.form and request.form['access_token']:
access_token = request.form['access_token']
else:
message = json.dumps({'message': 'Invalid or missing token', 'success': False})
return Response(response=message, status=401, mimetype='text/plain')
if access_token:
#TODO: validate_token(access_token)
Thank you
Author of flask-jwt-extended here. That's a great question. There is currently no supported way to do that in the extension, the grabbing the token from the request and decoding it are tightly coupled together. This would be hard to de-couple because there is a lot of conditional things that are going on when the full decode chain runs. For example, checking the CSRF value only if the request is sent in via a cookie, or differentiating between an access and refresh token for the sake of the blacklisting feature.
A generalized function could be created, it's signature would look something like decode_and_verify_jwt(encoded_token, is_access_token=True, check_csrf=False). However, this would complicate the rest of the code in flask_jwt_extended and be a rather confusing function to use for the general case.
I think in this case it would be easier just to add a fourth lookup in the extension, so you could use something like:
app.config['JWT_TOKEN_LOCATION'] = ['headers', 'forms']
app.config['JWT_FORM_KEY'] = 'access_token'
# Use the rest of the application normally
If you want to make a ticket on the github page so I can track this, I would be happy to work on it.

Designing URLs without verbs for operations related to user in a REST API

I'm building REST API.
I have following structure
GET /user/{id} - get
POST /users - Create user
PUT /users/{id} - Update user
DELETE /users/{id} - Delete user
The problem is following. As I got from many tutorials/articles - it is bad practice to use action in URL. But what to do with such actions like:
check email (is unique)
recover user by email
?
Assume user registration. User submits form ( POST /users ) and I need to check if email is unique. Do I need to do it in same api method and return validation errors as response body?
Or do I need to create something like
POST /users/email
And what about user recovering by email? Where do I need to do it? Because recover is verb
POST /users/recover
I'm not sure, that I'm doing it right and I can't find correct explanation for that situation.
Validating the e-mail and registering the user
If you want, you can have an endpoint to check whether an e-mail is already registered or not. It's up to your requirements. So, you can have something as following and then send the e-mail which will be validated in the request payload:
POST /users/email/validation
{
"email": "mail#example.com"
}
The endpoint above can be invoke, for example, when the user completes the e-mail field of your account registration form.
However, do not forget checking if the e-mail is already registered when creating a user:
POST /users
{
"firstName": "John",
"lastName": "Doe",
"email": "mail#example.com",
"password": "123456"
}
If an e-mail is already registered, you could consider returning a 409 Conflict status code and a payload that includes enough information for a user to recognize the source of the conflict.
Recovering the password
I'm unsure if this is your requirement, because of this I posted a comment asking for clarification. I presume you are trying to recover the password of a user, assuming the user has no more access to their account.
If so, you could have an endpoint as following and then send the e-mail of the user in the request payload:
POST /users/password/recovery
{
"email": "mail#example.com"
}
Then your server can send a link with a token to the e-mail specified in the payload. Only send the e-mail if the e-mail specified in the payload is registered in your application, of course.
The link should take the user to a page where they will enter the new password and, when submitting, an endpoint to replace the password of the user will be invoked, sending the token and the new password to the server:
PUT /users/password?token=SomeValueGoesHere
{
"password": "654321"
}

Posting data to Silex app ( jwt authentication using cnam/security-jwt-service-provider )

I am creating web service using silex micro framework. This is first time i am using it and I dont have prior knowledge on symfony. I could be able to understand how silex works and how to write controller providers , service providers etc ..
I couldnt work out authentication for my webservice.
I want to use JWT authentication and I found this cnam/security-jwt-service-provider extending firebase/php-jwt.
I set it up right and I get this output when I access protected resource
{"message":"A Token was not found in the TokenStorage."}
which is correct.
Question: I want to post the username , password to application and get token back. ( username=admin , password=foo )
I am using postman chrome extension ( also used Advanced rest client ) to post values to url ( http://silex.dev/api/login)
Post data I am sending
Key=> username Value=> admin
Key=> password Value=> foo
I also tried
Key=> _username Value=> admin
Key=> _password Value=> foo
Aldo tried key vaule pairs in basic auth headers.
response I get id
{
"success": false,
"error": "Invalid credentials"
}
When I debug the Application I see no post data at all.
$vars = json_decode($request->getContent(), true);
I get null $var.
PS: I know I will get a valid token back if I get these values posted correctly because I edited values from empty to correct values in breakpoint.
Apparently I should send data in json format and should set content-type appication/json
eg:
{
"_username":"admin",
"_password":"foo"
}
and response will something be like
{
success: true
token: "eyJ0eXAiOisKV1diLCJfbGgiOhJIjzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJleHAiOjE0Mzk5MDUxMjh9.DMdXAv2Ay16iI1UQbHZABLCU_gsD_j9-gEU2M2L2MFQ"
}