fastapi swagger not sending the token with the url - authorization

The fastapi swagger not sending token with the header. Even though i login through the authorization button of swagger.
this is the url it is showing: curl -X GET "http://localhost:8000/locations/?limit=100" -H "accept: application/json" -H "Authorization: Bearer undefined"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/createtoken")

If you want FastAPI's SwaggerUI to include your token in the API calls, make sure that your /users/createtoken endpoint is including the 2 required keywords in the response.
access_token: this should be your token value
token_type: the value of this should be Bearer
So your response should be something like,
{
access_token: 'abcdefg12345token',
token_type: 'Bearer'
}
If your endpoint is returning,
{
token: 'abcdefg12345token'
}
any SwaggerUI API calls will just show undefined for the token bearer value.

Related

Getting error 401 Unauthorised: Missing bearer authentication in header

API Documentation
This is the documentation for the available API endpoints, which are built around the REST architecture. All the API endpoints will return a JSON response with the standard HTTP response codes and need a Bearer Authentication via an API Key.
Base url
https://app.popify.site/api
Retrieve a user
curl --request GET \
--url 'https://app.popify.site/api/user' \
--header 'Authorization: Bearer {api_key}' \
Getting error 401: Missing bearer authentication in header, though I'm using correct api key.
If it is a JWT token you are passing, I'd suggest you to go to JWT decode and paste your encoded token to see what all information it consists. Ideally. roles and user related information is available in payload, if some of it is not enrolled or available on the authorization server, it will result in 401 Unauthorized.
curl --request GET \
--url 'https://app.popify.site/api/user' \
--header 'Authorization: Bearer {api_key}' \
wrap your authorization with quotes and do the same with bearer like this:
--url 'https://app.popify.site/api/user' \
-- header "Authorization ": "Bearer {api key} "
using fetch API:
const result = async getBalance(){
await fetch("https://foma.line.pm/balance", {
method: "get",
headers: {
"Authorization": " Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIU "
}}).then(response => response.json()).then(data => console.log(data)
)
}

Refreshing JWT in Flask returns "Only access tokens are allowed"

I have a strange problem with refreshing JWT token that I can't seem to find a solution for online.
My simple method for login:
#app.route("/api/login", methods=['POST'])
def app_login():
json = request.json
form = AppLoginForm.from_json(json)
password = json.get('password')
mobile = cleanup(json.get('mobile'))
user_found = User.query.filter(and_(User.mobile == mobile, or_(User.user_type == UserType.dashboard_user.value, User.user_type == UserType.end_user.value, User.user_type == UserType.dashboard_and_end_user.value))).first()
if user_found: #found
if bc.check_password_hash(user_found.password, password):
access_token = create_access_token(identity=user_found.mobile)
refresh_token = create_refresh_token(identity=user_found.mobile)
return send_response(True, None, { "access_token":access_token,"refresh_token":refresh_token }, 200)
else:
return send_response(False,[messages.WRONG_PASS], None, 406, {"case": UserLoginMeta.wrong_password.value})
My simple method for refreshing the JWT token:
#app.route('/api/refresh', methods=['POST'])
#jwt_refresh_token_required
def refresh_token():
''' refresh token endpoint '''
current_user = get_jwt_identity()
return send_response(True,None, [{ "access_token":create_access_token(identity=current_user)}])
Calling it the normal way with refresh token fails, and calling it with access token also fails:
Sending access token -> gives {"msg":"Only refresh tokens are allowed"}
curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MTAzNDczNDksIm5iZiI6MTYxMDM0NzM0OSwianRpIjoiODk4YjU1YmQtZjQzOS00OTE4LTkzZWQtN2UwMDNlZmEyM2M0IiwiZXhwIjoxNjEwNzc5MzQ5LCJpZGVudGl0eSI6Ijk2NjU0MTgyMjY3OSIsImZyZXNoIjpmYWxzZSwidHlwZSI6ImFjY2VzcyIsInVzZXJfY2xhaW1zIjp7ImlkZW50aXR5IjoiOTY2NTQxODIyNjc5IiwiZGV2aWNlIjp7ImlkIjoxMDk3NCwiSU1FSTEiOiIzNTI3MTQ0ODAxMjU2NzMiLCJJTUVJMiI6IjM1MjcxNDQ4MDE3NzY3NCIsInVuaXF1ZV9kZXZpY2VfaWQiOiJEZXNlcnQyMDAwMDAwMTY2In0sIndhcnJhbnR5Ijp7ImlkIjoyNjgsInNlcmlhbF9udW1iZXIiOiJXLTI3MzciLCJzdGF0dXMiOjIsInN0YXR1c190ZXh0IjoiQWN0aXZlIiwiZXhwaXJ5X2RhdGUiOiIyMDIzLzAxLzA2IiwibW9udGhzX2xlZnQiOjI0LCJkYXlzX2xlZnQiOjV9LCJhem9tX2NhcmUiOm51bGwsInVzZXIiOnsiaWQiOjM5OSwibW9iaWxlIjoiOTY2NTQxODIyNjc5IiwiZW1haWwiOiJhLm5hd2FmQGF6b210ZWNoLmNvbSIsImZpcnN0X25hbWUiOiJBYmVlciIsImxhc3RfbmFtZSI6Ik5hd2FmIn19fQ.PkFwQfIwStFkt3pCkZK919H203rDpLOD-96kcNEcRHw" -X POST http://localhost:5000/api/refresh
Sending refresh token -> gives {"msg":"Only access tokens are allowed"}
curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MTAzNDczNDksIm5iZiI6MTYxMDM0NzM0OSwianRpIjoiNDQxNzViNDYtNDZmZi00ZDUxLThmYzQtZTYwNjY4ZDlmNTU1IiwiZXhwIjoxNjEyOTM5MzQ5LCJpZGVudGl0eSI6Ijk2NjU0MTgyMjY3OSIsInR5cGUiOiJyZWZyZXNoIn0.VdevyrbAJL78TwNrPIPlWnyiB3swCtbg9cLwCMvmU8w" -X POST http://localhost:5000/api/refresh
Why is that??
I found the cause.
I have implemented a handler method on #app.before_request and my logic was broken and it has overridden the normal behavior of refresh token.
After I removed it, it worked Ok

Keycloak error : Code not valid - for client token request

Few days Ago I have integrate keycloak with my php application.
Which working fine. Now I am trying to do same thing for my vue js app.
In 2nd step (for client token request using authorization code) I am getting 400 error.
Response Message "Code not valid".
1st step : (inside mounted )
const AUTHORIZE_URL = 'auth/realms/rstore/protocol/openid-connect/auth';
const params = {
'response_type': 'code',
'redirect_uri': 'http://localhost:8080/sso/callback',
'client_id': client_id,
'nonce': uuid(),
'state': uuid(),
'scope': 'openid profile email'
};
window.location = baseUrl + AUTHORIZE_URL + '?' + queryString.stringify(params);
2nd step : (For client token request)
let url = baseUrl + ACCESS_TOKEN_URL;
let params = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'http://localhost:8080/sso/callback',
'client_id': client_id,
'client_secret': client_secret
};
let result = fetch(url, {
method: 'POST',
body: queryString.stringify(params),
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // ,
}
})
.then(resp => {
return resp.json();
})
.catch(error => {
throw new Error('FetchError in request to ES: ' + error.toString())
})
I also tried from command prompt --->
curl -X POST 'https://example.com/auth/realms/nstore/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'grant_type=authorization_code' \
--data-urlencode 'code=095516b7-e545-4b02-9dad-ec9c6366e0e4.33e1f298-a440-4bdc-9118-96ed669cabcd.e1c5d85f-3441-490d-a1fd-eb3b00d3c47c' \
--data-urlencode 'client_id=vue' \
--data-urlencode 'client_secret=b329ade3-2b71-4e3b-ab25-926cb32c5c8c' \
--data-urlencode 'redirect_uri=http://localhost:8080/sso/callback'
output same ---> {"error":"invalid_grant","error_description":"Code not valid"}
The "Code not valid" error message is a general one. It may have one of the following meanings:
http://localhost:8080/auth/realms/{realm_name}/protocol/openid-connect/auth
code is not valid, or is valid but incorrently URL encoded
the code is correct, but it has been already used by other user
session
Each authorization code can be used only once, to generate single new access token. As such, generating multiple access tokens from one code is not possible.
One reason why you may be receiving this error is because authorization code was already used, either by Postman or by web application.
Solution : regenerate the client_secret in the keycloak server for your realm and then do the complete process again and you will get the accesstoken and referesh token.
Note : Each authorization code can be used only once, to generate single new access token. As such, generating multiple access tokens from one code is not possible.

Request rejected with Options when fetching the VPCs with Authorization header

Generating the request to list the vpc details with IAM token which is kept in authorization header - The request has been generated from React App -
https://urls.cloud.ibm.com/v1/vpcs?version=2019-08-06&generation=1
Configuration
config = {
headers: {
"Authorization": "Bearer lmtmlmlm",
"Access-Control-Allow-Origin": "*"
}
}
The request was failed during the pre-flight request, it seems that the browser request headers are asking the server for permissions to make the actual request.
Can you suggest to overcome the problem.
The instructions here worked well for me: https://cloud.ibm.com/docs/vpc-on-classic?topic=vpc-on-classic-creating-a-vpc-using-the-rest-apis
I noticed you used the url: https://urls.cloud.ibm.com while these docs suggested https://us-south.iaas.cloud.ibm.com
rias_endpoint="https://us-south.iaas.cloud.ibm.com"
iam_token='Bearer zzzrandomstuff...eyJraWQiOiIyMDE5MDUxMyIsImFsZyI6IlJTMjU2In'
version="2019-05-31"
curl -X GET "$rias_endpoint/v1/vpcs?version=$version&generation=1" -H "Authorization: $iam_token"

Using Taxee.io API

I'm trying to access the Taxee.io API using the request npm module. The documentation is slightly poor and the difference between the Mashape info and the website's info is confusing.
https://taxee.io/
The docs have one example of a request here.
curl 'https://taxee.io/api/v2/calculate/2017' -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJBUElfS0VZX01BTkFHRVIiLCJodHRwOi8vdGF4ZWUuaW8vdXNlcl9pZCI6IjU4NDQ4MTA4Mzg2NjhhMTU4ZDU0ZmIzNSIsImh0dHA6Ly90YXhlZS5pby9zY29wZXMiOlsiYXBpIl0sImlhdCI6MTQ5OTA1MzU0NX0.pOwC5JEC7trLaaZVgHHGu_rvN0-EGa3RMm8BgJ-M9gk' -H 'Content-Type: application/x-www-form-urlencoded' --data 'state=NC&filing_status=married&pay_periods=26&pay_rate=116500&exemptions=2'
I however want to use the request npm module and am struggling to bridge the gap in how it will work in my express app.
const request = require('request');
request.post('https://taxee.io/api/v2/calculate/2017', {
'auth': {
'Bearer': 'mykey'
}
});
This is what I have thus far. Any help is appreciated.
Keep in mind that properties are case sensitive in JavaScript. You must pass the bearer token under the key bearer and not Bearer.
To replicate the Content-type and pass data, use the form support of the library.
E.g. like this:
{
auth: {
bearer: '<token>',
},
form: {
state: 'NC',
// ...
},
}