how can i build the authentication using symfony 6 and raeact js? - reactjs

In my App i don t need a registration feature so i added a user in the database manually ,Actually I tried with the LexiJWTAuthenticationBundle i followed the documentation but unfortunately when I use the cURL to send a request i get the following error
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.52 (Win64) OpenSSL/1.1.1m PHP/8.1.4 Server at localhost Port 443</address>
</body></html>```
**the cURL request is
curl -X POST -H "Content-Type: application/json" https://localhost/api/check_login --data '{"email":"johndoe#gmail.fr","password":"test"}' -k
Moreover frankly i m confused about the logic of the bundle so im worried if i need a controller or not .
However in the frontENd i m using reactJS i just sent a post request using axios
but when i hit submit in the network when i inspect i get
{
"code": 401,
"message": "JWT Token not found"
}

I think documentation is only showing an example. Not sure if that works out of the box because after installing it, I haven't seen a new Controller to handle the login_check route. In fact, ask to add the route manually, without referring a resource.
To generate a Token from a user, in a controller you will need to instantiate Jwt.
// src/Controller/AuthController.PHP
use App\Entity\User;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
class AuthController
{
private JWTTokenManagerInterface $jwt;
public function __construct(JWTTokenManagerInterface $jwt)
{
$this->jwt = $jwt;
}
#[Route(path: '/token', name: 'api_auth_token')]
public function login(Request $request): Response
{
// Code to retrieve your user
// [...]
// User must extends UserInterface for Lexik to work properly
$token = $this->jwt->create($user);
// return the token
}
This code will show you how to create the token, but not to login. You will have to check your authentication flow.
Side note: DonĀ“t confuse hashing the password with generating a token. You will need to do both things separately
I recommend you to look for the service you need by exploring autowirng:
php bin/console debug:autowiring jwt

Related

Http get method for Splunk saved search using access token

What would be the correct HTTP get request call syntax to fetch saved search data from Splunk if we're accessing it through an access token?
My curl command is working but http.get is not.
curl command:
#os.system('curl -H "Authorization: Bearer <token>"
<baseurl>:8089/services/search/jobs/export --data search="savedsearch abc_backup_status" -d output_mode=csv')
request call ::::
BASE_URL = '<baseurl>:8089/services/search/jobs/export'
data = {"search":"savedsearch abc_backup_status"}
headers = {'Authorization': "Bearer <token>"}
auth_response = requests.get(BASE_URL, headers=headers, data = data, verify=False)
this is giving 400 errors.
The curl options -d OR --data imply a POST method by default.
From: https://man7.org/linux/man-pages/man1/curl.1.html
-d, --data <data>
(HTTP MQTT) Sends the specified data in a POST request to
the HTTP server, in the same way that a browser does when
a user has filled in an HTML form and presses the submit
button. This will cause curl to pass the data to the
server using the content-type application/x-www-form-
urlencoded. Compare to -F, --form.
It is interesting that Splunk Docs claim that search/jobs/export takes a GET, but you're creating a job to immediately export, which feels like a POST type of operation.
Also I notice that your search starts with the savedsearch command, if that's a regularly scheduled savedsearch, you may want to GET saved/searches/{name}/history to get the last execution SID, followed either by the results or events endpoint of that already executed job, instead of a new search.... but that's a use case question

Unable to access the access code and refresh token of AAD Microsoft App

I'm trying to automate the file transfer between one drive and Linux. Hence I need to generate the access token and refresh token.
My POST URL is
https://login.microsoftonline.com/common/oauth2/v2.0/token?grant_type='authorization_code'&client_id=XXXXXXXXXXXXXX&code=XXXXXXXXXXXXX
getting below error as below
{
"error": "invalid_request",
"error_description": "AADSTS9001442323: The request body must contain the following parameter: 'grant_type'.\r\nTrace ID: 55c2b449-381b-41844ads5a2f-b2b7-451d65188500\r\nCorrelation ID: bf082e8f-99be-41e0-87dd-756894601365\r\nTimestamp: 2020-04-27 17:54:21Z",
"error_codes": [
90043234144
],
"timestamp": "2020-04-27 17:54:21Z",
"trace_id": "55cadsasdad2b449-381b-412f-b2b7-451d65188500",
"correlation_id": "bf0asdadada82e8f-99be-41e0-87dd-75688dasda94601365",
"error_uri": "https://login.microsoftonline.com/error?code=90014486"
}
You should specify application/x-www-form-urlencoded as the value of the header Content-Type. Then this error will not exist.
But based on your previous post, you have set the application/x-www-form-urlencoded. So if it's not the reason for this issue, please provide more details: Where are you generating the access token? In Postman? Could you provide a screenshot?
But there is another error. You should use grant_type=authorization_code instead of grant_type='authorization_code'.
And you should provide some other parameters. See this sample: Request an access token.

Interface Between Google Sign-in and MailKit

I am writing an app in WPF (Windows 10 desktop) that should
include a component where the user can download message headers
and messages from G-Mail.
I am trying to use MailKit to interface with G-Mail via a secure
connection (without having to turn on "allow less-secure apps"
for G-Mail) and download messages with POP3. I am a bit confused
as to the proper procedure.
FYI: I know next to nothing about OAuth and TLS, so KISS please.
I have created and downloaded a JSON file for OAuth 2.0 from Google.
I have visited the FAQ for MailKit, and the following section
seems relevant, but I'm not sure as to what I should plug in
to the interface.
(Please see the code below.)
For "password", would that be the password for the account?
I'm not sure as to what to give for
"your-developer-id#developer.gserviceaccount.com".
.........................................................
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#ProtocolLog
.........................................................
From the Q & A:
How can I log in to a GMail account using OAuth 2.0?
The first thing you need to do is follow Google's instructions for
obtaining OAuth 2.0 credentials for your application.
Once you've done that, the easiest way to obtain an access token is to
use Google's Google.Apis.Auth library:
var certificate = new X509Certificate2 (#"C:\path\to\certificate.p12", "password",
X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential (new ServiceAccountCredential
.Initializer ("your-developer-id#developer.gserviceaccount.com") {
// Note: other scopes can be found here: [links]
Scopes = new[] { "https mail google com " },
User = "username#gmail.com"
}.FromCertificate (certificate));
bool result = await credential.RequestAccessTokenAsync (CancellationToken.None);
// Note: result will be true if the access token was received successfully
// Now that you have an access token (credential.Token.AccessToken), you can
// use it with MailKit as if it were the password:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// use the access token as the password string
client.Authenticate ("username#gmail.com", credential.Token.AccessToken);
}
My next question: Would the user be able to access their own account(s)
with my app without having to follow the same procedure?
IOW: Will the credentials that I've downloaded work for any account?
... or allow access only to the account from which the credentials
were created?
If the credentials are only good for my own account, then I'll have to
do something else.
Would Google Sign-In be a better approach?
I've downloaded the example code for .NET from Google:
https://github.com/googlesamples/oauth-apps-for-windows
I've built and ran ran "OAuthConsoleApp", as well as "OAuthDesktopApp".
It would seem that I am getting a secure connection from those,
as I have gotten the following output:
.........................................................
redirect URI: http 127.0.0.1:64003
Listening..
Authorization code: qwerty ...
Exchanging code for tokens...
Send the request ...
GetRequestStream ...
await stream.WriteAsync ...
Get the response ...
responseText ...
{
"access_token": "qwerty ...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "qwerty ...",
"id_token": "qwerty ..."
}
Making API Call to Userinfo...
+++ userinfoResponseText : {
"sub": "117108120545711995673",
"name": "My Name",
"given_name": "My",
"family_name": "Name",
"picture": "qwerty ...",
"locale": "en"
}
.....................................................
I see that I have an "access_token" in the response and I thought
that I could plug that in to the "client.Authenticate" method for
MailKit as the password (as mentioned in the docs for MailKit):
string access_token = tokenEndpointDecoded["access_token"];
client.Connect ("pop.gmail.com", 995, SecureSocketOptions.SslOnConnect);
client.Authenticate ("username#gmail.com", access_token);
It threw an exception:
.....................................................
"POP3 server did not respond with a +OK response to the AUTH command."
at MailKit.Net.Pop3.Pop3Client.Authenticate(Encoding encoding,
ICredentials credentials, CancellationToken cancellationToken)
at MailKit.MailService.Authenticate(String userName, String
password, CancellationToken cancellationToken)
at
NS_MailKit_01.Pop3.cls_mailKit_Pop3_01.connect_and_authenticate(Object
p3_client, String p_access_token)
in :\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\Mail_Kit_01\MailKit_01.cs:line
465
at
LIB1_01_G_Mail_Auth.cls_G_mail_authorization.str_token_NTRF.invoke_access_token(String
p_access_token)
in K:\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\OAuth\oauth-apps-for-windows\OAuthConsoleApp\LIB1_01_G_Mail_Auth\G_Mail_Auth_01.cs:
line 95
at
LIB1_01_G_Mail_Auth.cls_G_mail_authorization.d__13.MoveNext()
in K:\Software_Develpoment_Sys_03_K\MIME_EMail\TEST_02\OAuth\oauth-apps-for-windows\OAuthConsoleApp\LIB1_01_G_Mail_Auth\G_Mail_Auth_01.cs:line
343
.....................................................
Does anyone know how I could get a "credential" object from
the Google interface that I could use with MailKit?
Any help would be appreciated.
Thanks!
For "password", would that be the password for the account?
No. It would be the password for your PKCS12 file containing your X.509 Certificate and your private key.
I'm not sure as to what to give for "your-developer-id#developer.gserviceaccount.com".
You need to register yourself and your application with Google's Developer program which will give you a developer id to use. You need to follow their directions.

How to properly connect cloudant + sag

I'm working in getting a connection to cloudant done.
The following is using sag library for php:
<?php
header('Content-Type: text/html; charset=utf-8');
require_once('../../src/Sag.php');
//this credentials are from API key
$uName="";
$pName="";
$sag = new Sag('user.cloudant.com');
$sag->login($uName, $pName);
$sag->setDatabase('test');
try {
$result = $sag->get('/test/_design/wordsP/_view/errores');
echo ($result);
}
catch(Exception $e) {
error_log("Something's wrong");
var_dump($e);
}
?>
However I'm not getting expected result (). The view does work, if used just in the url bar.
The response is:
object(SagException)#3(6){
[
"message:protected"
]=>string(50)"Sag Error: cURL error #7: couldn't connect to host"[
"string:private"
]=>string(0)""[
"code:protected"
]=>int(0)[
"file:protected"
]=>string(73)"/home2/.../public_html/clant/src/httpAdapters/SagCURLHTTPAdapter.php"[
"line:protected"
]=>int(134)[
"trace:private"
]=>array(3){ .............
Is there something I'm not using corretly in the php script? (removed current password + username as well as account, but they're there).
Curl error 7 means you are unable to connect to the host or proxy:
CURLE_COULDNT_CONNECT (7)
Failed to connect() to host or proxy.
Source: http://curl.haxx.se/libcurl/c/libcurl-errors.html
When you connect to the URL from your browser if your browser is using a proxy, you will also need to configure sag to use that proxy.
Also, when you say that you replaced the account in your code example, did you mean that you replaced user in $sag = new Sag('user.cloudant.com'); with your actual username? If not, you will need to use your actual username.

NetworkError: 405 Method Not Allowed AngularJS REST

In AngularJS, I had the following function, which worked fine:
$http.get( "fruits.json" ).success( $scope.handleLoaded );
Now I would like to change this from a file to a url (that returns json using some sweet Laravel 4):
$http.get( "http://localhost/fruitapp/fruits").success( $scope.handleLoaded );
The error I get is:
"NetworkError: 405 Method Not Allowed - http://localhost/fruitapp/fruits"
What's the problem? Is it because fruit.json was "local" and localhost is not?
From w3:
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response MUST include an Allow header
containing a list of valid methods for the requested resource.
It means the for the URL: http://localhost/fruitapp/fruits The server is responding that the GET method isn't allowed. Is it a POST or PUT?
The angular js version you are using would be <= 1.2.9.
If Yes, try this.
return $http({
url: 'http://localhost/fruitapp/fruits',
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
I had a similar issue with my SpringBoot project, I was getting the same error in the browser console but I saw a different error message when I looked at the back-end log, It was throwing this error: "org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'DELETE' not supported " It turned out that I was missing the {id} parameter in the back-end controller:
** Wrong code :**
#RequestMapping(value="books",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
** Correct code :**
#RequestMapping(value="books/{id}",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
For me, it was the server not being configured for CORS.
Here is how I did it on Azure: CORS enabling on Azure
I hope something similar works with your server, too.
I also found a proposal how to configure CORS on the web.config, but no guarantee: configure CORS in the web.config. In general, there is a preflight request to your server, and if you did a cross-origin request (that is from another url than your server has), you need to allow all origins on your server (Access-Control-Allow-Origin *).

Resources