LexikJWTAuthenticationBundle with ionic app - authentication

I have seen many post on this subject, but i can't make a correct request, regardless all of my tests.
I hope anyone could help me on this.
My current configuration :
I work with wamp - apache 2.4.9 -- php 5.5.12
I work with symfony3
i add all rewrite rules in my vhost :
RewriteEngine On
RewriteCond %{HTTP:Authorization} ^(.)
RewriteRule . - [e=HTTP_AUTHORIZATION:%1]
On backend, my security.yml is :
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api_doc:
pattern: ^/api/doc
anonymous: true
api_login:
pattern: ^/api/login
provider: fos_userbundle
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
require_previous_session: false
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
api:
pattern: ^/api
stateless: true
provider: fos_userbundle
lexik_jwt:
authorization_header:
enabled: true
prefix: Bearer
query_parameter:
enabled: true
name: Bearer
throw_exceptions: true
create_entry_point: true
Configuration of fosuserbundle :
fos_user:
db_driver: orm
firewall_name: main
user_class: UserBundle\Entity\User
group:
group_class: UserBundle\Entity\Group
form:
type: UserBundle\Form\Type\GroupFormType
profile:
form:
type: UserBundle\Form\Type\ProfileFormType
And side of client, i use ionic with angular js, and i try to get the token with :
var loginData = {
username: this.login.username,
password: this.login.password
};
console.debug(loginData);
$http({
url: 'http://app.local/app_dev.php/api/login_check',
method: 'POST',
data: loginData,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
ignoreAuthModule: true
})
.success(function (data) {
console.log("Success -- login ok with ".data);
$scope.token = data;
})
.error(function (data) {
console.log("ERROR -- login fail with ", data);
$scope.token = data;
});
that's always return me 'bad credentials'
But my test with curl send me a token
curl -X POST http://app.local/api/login_check -d _username=username -d _password=pass
I have test to prefix _ my login data, change configuration
If anyone have an idea ??
EDIT :
Maybe i have found my problem.
This request curl work fine :
curl -X POST http://app.local/api/login_check -d _username=username -d _password=pass
But this one doesn't work :
curl -X POST http://app.local/app_dev.php/api/login_check -d '{"username": "user", "password": "pass"}'
I search one solution for solve it, but i guess angular http method cannot send two parameters
EDIT 2 :
This request works fine :
curl -X POST http://app.local/app_dev.php/api/login_check -d '{"_username": "user", "_password": "pass"}' -H "Content-Type: application/json"
I search a solution for copy this request with angular http object
EDIT 3 :
I make my angular request like this :
var loginData = {
_username: this.login.username,
_password: this.login.password
};
$http({
url: 'http://app.local/app_dev.php/api/login_check',
method: 'POST',
data: loginData,
headers: {'Content-Type': 'application/json'}
})
.success(function (data) {
console.log("Success -- login ok with ".data);
})
.error(function (error) {
console.log("ERROR -- login fail with ", error);
});
And my javascript console print an error :
XMLHttpRequest cannot load http://app.local/app_dev.php/api/login_check. Response for preflight has invalid HTTP status code 404
EDIT 4 :
I ddin't found the solution ...
It seems CORS request is the problem. i try do reset all headers in my mobile app, nothing has changed.
I try to install nelmioCorsBundle for authorize OPTIONS headers and control my configuration, nothing has changed
I have installed the sandbox (https://github.com/slashfan/LexikJWTAuthenticationBundleSandbox) and i have exactly the same problem.
When i try to execute curl request, i can get my token. When i use angular/ionic app, i have the error :
https://github.com/slashfan/LexikJWTAuthenticationBundleSandbox
XMLHttpRequest cannot load http://app.local/app_dev.php/api/login_check. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://localhost:8100', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.
If anyone have a new idea ?? i don't know what i can test now :s
PS : which version of angular is working with demo app in the LexikJWTAuthenticationBundleSandbox ?

In the first (working) request you are using _username as field with value "username" and _password as field with value "pass".
In the second you are using username (instead of _username) as field with value "user" and password (instead of _password) as field with value "pass".
Change your second request to:
curl -X POST http://app.local/app_dev.php/api/login_check -d '{"_username": "username", "_password": "pass"}'
And it should work.
EDIT
Add the option -H "Content-Type: application/json, that gives:
curl -X POST http://app.local/app_dev.php/api/login_check -H "Content-Type: application/json" -d '{"_username": "username", "_password": "pass"}'
And it should work!
EDIT
It seems to be a CORS related issue.
Try to add the following in your angular application, before doing the POST request:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
Where app is your angular module (i.e. var app = angular.module(...)).

Related

Strava API: Create muted activity

Using Strava API v3 and create activity method, I'd like to mute activity. So, according to the docs, I should set hide_from_home to true.
However, the flag doesn't work correctly. Meaning, I'm receiving response containing:
"hide_from_home": false
And, activity is visible in Active Feed.
I tried to send the request via Flurl (C#) and curl (Postman).
The Flurl code looks more like a:
var rs = await host.AppendPathSegments("activities")
.WithOAuthBearerToken(accessToken)
.AllowAnyHttpStatus()
.PostUrlEncodedAsync(new Dictionary<string, dynamic>
{
{ "name", "😎 test from api" },
{ "type", "Walk" }, // https://developers.strava.com/docs/reference/#api-models-ActivityType
{ "sport_type", "Walk" }, // https://developers.strava.com/docs/reference/#api-models-SportType
{ "start_date_local", DateTime.Now.AddMilliseconds(-1).ToString("s", CultureInfo.InvariantCulture) },
{ "elapsed_time", 2 }, // In seconds
{ "hide_from_home", true },
})
.ReceiveString();
I tried to use dynamic, object and string as a dictionary value type and tried to pass true (as a boolean) and "true" (as a string), but none of these worked.
For curl, I imported example from the Strava Playground (Swagger UI) [Authorization removed in that example]:
curl -X POST "https://www.strava.com/api/v3/activities" -H "accept: application/json" -H "Content-Type: application/x-www-form-urlencoded" -d "name=Api&type=Walk&sport_type=Walk&start_date_local=2022-08-12&elapsed_time=2&hide_from_home=true"
So, the question: How to create muted activity via Strava API?

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.

Curl command works, but httparty request gives 403

I have a curl command that makes a POST request, and returns with the correct response:
curl --data 'apiKey=someKey&apiSecureKey=someSecureKey&apiFunctionName=update&apiFunctionParams={"id”:”777”,”user_password":"password","invalid_login_attempts":"0","active_flag":"1"}' https://api-server.com/api-path/file.php
Also, when using Postman, the request works if I check the "form-data" button and paste the same four parameters that are in the curl command above into the body of the Postman request. If I check the "x-www-form-urlencoded" button in Postman, I get a 403 response (see below), so that makes me think it is a header issue.
I need to duplicate this request using httparty. Here is my attempt:
options = {
body: {
apiKey: 'someKey',
apiSecureKey: 'someSecureKey',
apiFunctionName: 'update',
apiFunctionParams: '{"id”:”777”,”user_password":"password","invalid_login_attempts":"0","active_flag":"1"}',
}
}
response = HTTParty.post("https://api-server.com/api-path/file.php", options)
This request gives me a 403 repsonse code:
{"success":false,"response":"403","responseDesc":"Forbidden. Request is missing an API permission code.","params":{"id":"777","user_password":"password","invalid_login_attempts":"0","active_flag":"1"}}
If I try to add a header, such as:
options = {
headers: {'Content-Type' => 'multipart/form-data'},
body: {
apiKey: '20a030e47a28',
apiSecureKey: '3a4e409e0c9f0e72e697fc288a88d751',
apiFunctionName: 'update',
apiFunctionParams: '{"id":"603","user_password":"password","invalid_login_attempts":"0","active_flag":"1"}',
}
response = HTTParty.post("https://beta.fxptouch.com/classes/interface/user_profile.php", options)
I get a nil response.

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',
// ...
},
}

how set ajax call by rest api parse.com

I'm new in rest api and i'm trying to use the api rest to associate file to object:
curl -X POST \
-H "X-Parse-Application-Id: qS0KL*9lFLE**S3VMk" \
-H "X-Parse-REST-API-Key: nh3***MhcKJIfIt1Gm" \
-H "Content-Type: application/json" \
-d '{
"name": "Andrew",
"picture": {
"name": "...profile.png",
"__type": "File"
}
}' \
https://api.parse.com/1/classes/PlayerProfile
Can anyone explain me how to set the ajax call?And what is "name":"andrew"?Is this a column named andrew in my player profile?
This is my implementation of api,but the server responded me bad request 400:
$.ajax({
type: 'POST',
headers: {'X-Parse-Application-Id':'qS0KLMx5h9lFLG**yhM9EEPiTS3VMk','X-Parse-REST-API-
Key':'nh3G8D**hcKJIfIt1Gm','Content-Type': 'application/json'},
url: "https://api.parse.com/1/users",
data: {
"username": "francesco",
"picture": {
"name": "b3b47ce2-62dc-4861-a0ad-79cfffe9b07a-foto ste.jpg",
"__type": "File"
}
},
contentType: "application/json",
success: function(data) {
console.log(data );
},
error: function(data) {
console.log("ko" );
}
});
May the api -d is wrong in my implementation.What's means -d in curl?
The example in the guide shows how you can create a new PlayerProfile object and associate it with a File in a single request. Since you want to update an existing User (and not create a new one), you'll need to use the Update REST API request format. Use PUT instead of POST, then specify which user you're referring to by appending the object id to the endpoint URL: https://api.parse.com/1/users/{objectId}.