I am trying to POST username, password of auth to Laravel/Passport but it always return null
axios.post('http://localhost:8000/api/login', {
withCredentials: true,
auth: {
email: 'agent#test.com',
password: 'qwerty!##$%^'
}
})
.then(res => {
console.log(res);
})
PassportController.php
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['email'=>request('email')], 401);
// I return email to see value
// return response()->json(['error'=>'Unauthorised'], 401);
}
}
api.php
Route::post('login', 'PassportController#login');
I checked everything many times, feel everything is ok, but for some reason data not send to passport.
conosle log:
POST http://localhost:8000/api/login 401 (Unauthorized)
{email: null}
email: null
Laravel is probably accessing the POST data's values with request. The axios.post method's second parameter is the object sent as POST data, so you probably meant to just pass the email and password as top-level keys:
axios
.post(
"http://localhost:8000/api/login",
{
email: "agent#test.com",
password: "qwerty!##$%^"
},
{ withCredentials: true }
)
.then(res => {
console.log(res);
});
I suspect that you may be mixing up authentication in general with HTTP ("Basic") Authentication. The auth key is part of the config object that you can pass as a third parameter to axios.post, which would control just that. I do not think this is what you are after, but just adding it here for completeness. Note that basic auth accepts an username and a password:
axios
.post("http://localhost:8000/api/login", {}, {
withCredentials: true,
auth: {
username: "agent#test.com",
password: "qwerty!##$%^"
}
})
.then(res => {
console.log(res);
});
Finally I solved my issue, the problem is no need to send credentials and auth via axios because from back-end laravel accept post data not auth data, so I passed email and password via form-data not auth:
axios.post("http://localhost:8000/api/login", {
email: "agent#test.com",
password: "qwerty!##$%^"
})
.then(res => {
console.log(res);
});
Now I got token in back-end.
Related
I have a problem with sending POST request from Vue axios to laravel server with sanctum.
Firstly I'm getting token.
My route of api.php
Route::post('/get_token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required'
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
vue axios
this.$axios.post('/api/get_token', {
email: this.email,
password: this.password,
device_name: this.device_name,
}).then(response=>{...});
And when I send GET request with received token, it works correctly
vue axios
this.$axios.get('/api/book/all', {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken
}
}).then(response=>{...})
api.php
Route::middleware('auth:sanctum')->get('/book/all', 'BookController#all');
But when I try to send POST request, I get {"message":"Unauthenticated."} and 401 error
vue axios
this.$axios.post('/api/book/add', {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
},
data: {
title: this.addingTitle,
author: this.addingAuthor,
}
})
api.php
Route::middleware('auth:sanctum')->post('/book/add', 'BookController#add');
Sorry, I’m just a noob in web and don’t understand many things, hope you can help me.
If you use post then the 1st parameter is the URL and the 2nd one is the data your are posting. In your case it might make more sense to use:
this.$axios({
method: 'POST',
url: '/api/book/add'
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
},
data: {
title: this.addingTitle,
author: this.addingAuthor,
}
})
or if you want to still use .post then:
this.$axios.post('/api/book/add', {
title: this.addingTitle,
author: this.addingAuthor,
}, {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
}
})
Route (web.php)
Route::get('user', function () {
$user=Auth::user();
return response(['user_id'=>$user->id],200);
});
React.js fetch()
fetch('/user')
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
});
When visiting /user in a browser:
{"user_id":1}
When running the fetch() method:
Trying to get property of non-object
This is because $user=Auth::user(); is returning null.
I know this is not a csrf issue because returning static content (such as user_id=>1 ) works fine with the fetch method.
Here are the cookies being sent with the request:
Whats stopping the user session from working? Been messing with this for hours.
Just noticed that my picture shows cookies being returned, not sent.
Changed fetch() code to this and it worked:
fetch('/user',{
credentials: 'include' //Includes cookies
})
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
});
I am currently a beginner of react native and I want to know if I wanted to login and store user data using AsyncStorage, what key and value should be passed?
AsyncStorage.setItem('key', 'value');
UserLogin = () =>{
const { username } = this.state ;
fetch('https://www.example.com/React/user-login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
})
}).then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if(responseJson === 'Data Matched')
{
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
//Then open Profile activity and send user email to profile activity.
this.props.navigation.navigate('ProfileScreen', { username:username });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
If I were to say if logged in, then AsyncStorage.setItem('key', 'value');, then that could work if I want to store say the user's username so that I can display it on their profile page?
AsyncStorage parameters are both strings, so you can store serialised json data or just a plain string.
// Some code that logs someone in and gets an authentication token which then is stored
login(username, password).then(authenticationToken => {
AsyncStorage.setItem('token', authenticationToken)
})
// then somewhere else in your code
AsyncStorage.getItem('token').then(authenticationToken => {
console.log(‘the token’, authenticationToken)
})
I created a login API with JWT, I tested it with Postman and curl via terminal and it works great. But when I'm trying to get it to work using jQuery ajax and it responds with
POST http://router.dev/api/login 401 (Unauthorized)
This is suppose to be on login, to generate a token. This is the ajax code:
var authenticate = function(){
return $.ajax({
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
data: {email:'apitest#example.com',password:12346},
url: 'http://router.dev/api/login'
});
}
And this is the auth method I'm using:
public function authenticate(Request $request){
// grab credentials from the request
$credentials = $request->only('email', 'password');
//dd($credentials);
try {
config(['auth.providers.users.model' => \App\Usuarios::class]);
$token = JWTAuth::attempt($credentials);
// dd($token);
// attempt to verify the credentials and create a token for the user
if (! $token) {
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'));
}
Maybe it's something dull. Thanks in advance.
Trying to integrate APIs built in Laravel 5.4 with ionic 2 and struggling handle the error
What I want to do:
Authenticate the login using Laravel Password service ( OAuth2 ).
Once authenticated, it would return the access token.
Access Token is passed in the header in a GET API call to receive the
user details.
I am able to #1 and #2 but got stuck at #3.
Here is my code of login.ts
public login() {
this.showLoading();
this.auth.login(this.loginCredentials).subscribe(allowed => {
if (allowed) {
setTimeout(() => {
this.loading.dismiss();
this.nav.setRoot(HelloIonicPage)
});
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
auth is a service provider, that has login method.
//Function to get access token
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
return Observable.create(observer => {
var link = 'http://localhost/XXX/public/oauth/token';
var vars = {
password: "XXX",
username: "XXXXXX",
grant_type: 'password',
client_id: "XXXXX",
client_secret: 'XXXXXX',
scope: ''
}
this.http.post(link, vars)
.map(res => res.json())
.subscribe(
data => { let user = this.getUserFromAccessToken(data);
console.log(user);
observer.next(user);
},
err => { observer.error(err.json()); }
() => {
console.log('Completed..');
}
);
});
}
}
//Function to get user from the accessToken
private getUserFromAccessToken(oAuthData) {
let headers = new Headers({ 'Content-Type': 'application/json','Accept': 'application/json','Authorization': 'Bearer ' + oAuthData.access_token });
let options = new RequestOptions({ headers: headers });
let link = 'http://localhost/XXXX/public/api/v1/user';
return this.http.get(link, options)
.map(res => res.json())
.subscribe(
data => this.currentUser = data.user,
err => this.error = err
);
}
currentUser and error are defined as properties of the AuthService class.
How should I ensure that an error is thrown either in case the access token is not returned or user is not returned from the access token.