Trying to do a very simple api authentication using lumen 5.2
That is just check the header HTTP_key value to the hardcoded key value in lumen. If correct then process the api else throw an error.
I was able to implement it in php using the below code. I simply am not able to do the same in lumen. I previously used codeigniter only. So kind of new to the framework
public function auth() {
if (empty($_SERVER['HTTP_KEY'])) {
$_SERVER['HTTP_KEY'] = 0;
}
if (!($_SERVER['HTTP_KEY'] === $this->key)) {
$error = array('status' => 'Error', 'msg' => 'Authentication Failed');
$this->response($this->json($error), 401);
}
}
Related
So, I have integrated keycloak API endpoints in my Symfony project..
Regarding https://ultimatesecurity.pro/post/password-policy/ we have added 'not username' policy to test on creating new user within the app.
Idea is to delcare specific method with defined endpoint which will do this.
I was checking the documentation and could not find any endpoint that can check for password policy rules --> documentation
Idea for it:
$options = [
'headers' => $this->getAuthJsonHeaders()
];
try {
$endpoint = sprintf('auth/admin/realms/%s/', $this->realm);
$response = $this->request('GET', $endpoint, $options);
return $response;
} catch (\Exception $e) {
$this->exception('Can`t reset user password on Keycloak. ' . $e->getMessage());
}
This is what I get:
when dumping results
To get the list of the password policies being used by the Realm, you should call the following endpoint:
GET <KEYCLOAK_HOST>/auth/admin/realms/<YOUR_REALM>
from the JSON response extract the field:
passwordPolicy
which for instance if you have set Minimum length to 12 and Hashing Iterations to 27500 the passwordPolicy would be "length(12) and hashIterations(27500)"
I am creating a shopify app and currently, i want to register webhooks in my app so that if a customer is created, a notification/sms to sent to the admin.
According to my research, it can be registered through the shop settings but in this case, i want to register it via the app. But there are not enough resources to get this done.. Below is what i have but when i create a customer, my sms is not sent to the admin..
What could i be missing out now ?
VerifyWebhook
public function handle($request, Closure $next)
{
$hmac = request()->header('x-shopify-hmac-sha256') ?: '';
$shop = request()->header('x-shopify-shop-domain');
$data = request()->getContent();
// From https://help.shopify.com/api/getting-started/webhooks#verify-webhook
$hmacLocal = base64_encode(hash_hmac('sha256', $data, env('SHOPIFY_SECRET'), true));
if (!hash_equals($hmac, $hmacLocal) || empty($shop)) {
// Issue with HMAC or missing shop header
abort(401, 'Invalid webhook signature');
}
return $next($request);
}
Route
Route::post('webhook/shopify/customer-created', function(\Illuminate\Http\Request $request) {
// Handle customer created and sms or notification
})->middleware('webhook');
It looks like you are trying to verify webhook instead of creating one. Please go through below process
Create a webhook using simple request:
POST /admin/webhooks.json
{
"webhook": {
"topic": "customers/create",
"address": "https://whatever.hostname.com/",
"format": "json"
}
}
ofcourse you will have to pass shopify auth token in headers.
If you want to use a package to ease the process you can use: https://github.com/oseintow/laravel-shopify
your routes.php/web.php
Route::get('/register-webhook', 'WebhooksController#registerCustomerWebhook')->name('customer');
Route::get('/webhooks/customer-created', 'WebhooksController#customerCreated')->name('customerCreated');
and then import and use it -->
use Oseintow\Shopify\Facades\Shopify;
.
.
// create a webhook
public function registerCustomerWebhook(...){
Shopify::setShopUrl($shopUrl)->setAccessToken($accessToken)->post("admin/webhooks.json", ['webhook' =>
['topic' => 'customers/create',
'address' => 'https://whatever.hostname.com/path',
'format' => 'json'
]
]);
.
}
Verifying webhook:
public function customerCreated(...) {
if (Shopify::verifyWebHook($data, $hmacHeader)) {
// do your stuffs here in background
return response('Hello World', 200)
->header('Content-Type', 'text/plain');
} else {
return response('UnAuthorized', 401)
->header('Content-Type', 'text/plain');
}
.
.
}
Note:
Your endpoint must have proper ssl certificates installed
You need to respond to an webhook as quickly as possible. Its better to do your tasks in background.
Let me know if there is any confusion.
I'm using Lumen with Dingo API for building an API. My registration function checks to see if the email specified already exists.
Using Dingo API Helpers to return an error response if the email already exists in the database.
Dingo\Api\Routing\Helpers
isEmailTaken function:
private function isEmailtaken($email) {
$userExists = User::where('email', $email)->count();
if($userExists) {
$return['error'] = true;
$return['message'] = "It appears you already have an account with us.";
return $return;
} else {
$return['error'] = false;
return $return;
}
}
The registration function calls that function and returns an error:
$validateEmail = $this->isEmailtaken($email);
if ($validateEmail['error'] == true) {
return $this->response->errorBadRequest($validateEmail['message']);
}
It outputs the correct error message with the correct error code in the json response:
"{"message":"It appears you already have an account with us.","status_code":400}"
However, the status generated by the response in the header is OK and code is 200.
status_code 400 bad request will return when the request data is not valid
below code help to return the response with custom status_code
use Illuminate\Http\Response;
return response()->json(['message' => 'It appears you already have an account with us.'])->setStatusCode(400);
Also the shorted way to validate unique emailID from the laravel validation like below
$rules = array(
'email'=>'required|email|unique:user',
);
$validator = Validator::make($request->all(), $rules);
if (!$validator->passes()) {
return response()->json([ 'message' => $validator->messages()])->setStatusCode(400);
}
i had developed JWT web token based laravel 5.3 project. Now i was struggled in authentication process because i have create new model like UserAccountsModel and also controller was different.The problem is token not generating. Here is my code
$credentials['Email'] = $request->get('username');
$credentials['Password'] = $request->get('password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
// if no errors are encountered we can return a JWT
return response()->json(compact('token'));
its only returning invalid_credentials..
so please any one can tell me where will i struggled and what are the configuration i am missing.
So I am developing Ionic app with Laravel back-end and using JWT authentication.
My question is...since im using 4 fields when registering a user, and only 2 when logging in (email and pass), I suppose that upon registration the token should be made of only those 2 fields...
This is the working sign up function:
public function signUp()
{
$credentials = Input::all();
if (User::whereEmail($credentials['email'])->first()) {
return Response::json([
'error' => 'User with given e-mail already exists',
], 409);
} elseif (User::wherePhone($credentials['phone'])->first()) {
return Response::json([
'error' => 'User with given phone number already exists',
], 409);
} else {
$user = User::create($credentials);
$token = JWTAuth::fromUser($user);
return Response::json(compact('token'));
}
}
However if I change $credentials = Input::only('email', 'password') the full user won't be created (since there are fields missing).
But even if I leave $credentials as-is, and make combinations like
$token = JWTAuth::fromUser(Input::only('email', 'password')) or parse e-mail and password to JSON, or something similar...I get a "Trying to get a property of non-object" error, or that array is given instead of an object to JWTAuth...
JWTAuth::fromUser(Input::only('email', 'password')) expects a User object.
If you wish to use credentials you can do something like this:
// grab credentials from the request
$credentials = Input::only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials)) {
return Response::json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return Response::json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return Response::json(compact('token'));
https://github.com/tymondesigns/jwt-auth/wiki/Creating-Tokens