jwt_authentication request ajax - symfony - javascript

I'm working with symfont and JSON Web Token and Symfony.
I'm trying to get jwt with ajax, but I get 401 (Unauthorized)
The problem is with ajax, because i try with postman and I can get the token.
here is my security.yaml
security:
encoders:
App\Entity\Users:
algorithm: bcrypt
providers:
users:
entity:
class: App\Entity\Users
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
login_app_manager:
pattern: ^/user/login
stateless: true
anonymous: true
provider: users
json_login:
check_path: /user/login
username_path: email
password_path: password
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
app_api_manager:
pattern: ^/mngr/api
stateless: true
anonymous: false
provider: users
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/api, roles: IS_AUTHENTICATED_FULLY }
here is my ajax
var data = {
'email':email,
'password':password
};
$.ajax({
type: "POST",
url: "/user/login",
contentType: "application/json",
data: JSON.stringify(data),
success: function(response) {
console.log(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('Error : ' + errorThrown);
}
});
please help me, thank you

Try post instead of ajax:
$(document).ready(function{
//form submit
$("form").submit(function(event){
var email = $('#email').val();
var password = $('#password').val();
$.post("/user/login",{
email:email, password: password
}).done(function(data){
})
})
});

In access_control add path
{ path: ^/user/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
instead of
{ path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
and make sure to include this path in routes.yaml
user_login:
path: /user/login
methods: ['POST']

Related

Nuxt-auth V5 how to get a user by id

My 'Login' endpoint works fine, and I set the 'propertyName' to 'access_token' as that is where the value for my token lives. I see 'Vuex' update my 'LoggedIn' status to true and I can also see the Token Response in the 'Network' tab of Chrome.
However, I'm really struggling to understand how the 'User' endpoint works.
The example is given:
auth: {
strategies: {
login: {
scheme: 'local',
token: {
property: 'access_token',
required: true,
type: 'Bearer',
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30
},
user: {
property: false,
autoFetch: true,
},
autoLogout: true,
endpoints: {
login: { url: '/registration/login', method: 'post', propertyName: 'access_token'},
user: {
url: '/registration/requests/1',
method: 'get',
propertyName: false
},
logout: {
url: '/registration/logout', method: 'post'
},
},
},
},
redirect: {
login: '/news',
},
},
The above is pretty much identical to mine, how does the 'User' endpoint, know which user is logged in?
I am using a third-party system for my authentication as I'm integrating an application into the third-party system. Their 'User' endpoint for REST requires an 'ID' or 'UserName' to return details about a particular user.
My 'Login' response contains 'UserName' which I could use to call the subsequent User endpoint (If I knew how).
Does anyone know how the User endpoint works? Essentially I need to call it something like this:
user: { url: '/users/${userId}', method: 'get', }

Nuxt-auth ..login network header gives me strange path seems like my locale route for login page

Iam trying to use nuxt-auth module with axios and it gives me "Cannot read property 'data' of undefined" ...and login headers gives strange path
"Request URL: http://aqar.abdullah.link/api/api/auth/login",any help please???
Nuxt.config.js
axios: {
baseURL:'http://aqar.abdullah.link/api',
auth: {
strategies: {
local: {
endpoints: {
login: { url: '/office/login', method: 'post', propertyName: 'data.token' },
user: { url: '/auth/me', method: 'post', propertyName: false },
logout: false
}
}
}
}
}
Login Method:
methods:{
async Login(){
try{
await this.$auth.loginWith('local', {
data:{
email: this.email,
password: this.password
}
})
this.$router.push('/')
}catch(e){
this.error = e.response.data
}
},
},
Api response on postman:
login page path in folders
I'm not sure, I used the exact same configurations and it worked for me.
But your nuxt.config.js file has a missing closing }, for the axios object.
it should look like this:
axios: {
baseURL: "http://aqar.abdullah.link/api"
},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: "/office/login",
method: "post",
propertyName: "data.token"
},
user: { url: "/auth/me", method: "post", propertyName: false },
logout: false
}
}
}
},
also make sure you have these modules in you nuxt.config.js as well:
modules: [
"#nuxt/http",
"#nuxtjs/auth",
"#nuxtjs/axios",
],

Node.js/Mongoose/lodash - server response: User Validation Failed: path `foo` is required

The error message being received is:
"User validation failed: email: Path email is required., display_name: Path display_name is required."
The error name being sent back is: ValidationError.
The code for the ajax call is:
function submit_new_user(display_name, email, password){
let user_data = new New_User(display_name, email, password);
console.log(user_data);
$.ajax ({
dataType: 'JSON',
data: user_data,
method:'POST',
url: 'http://localhost:3001/user',
success: (res)=>{
console.log(res);
},
error: (xhr, ajaxOptions, thrownError)=>{
console.log(xhr, ajaxOptions, thrownError);
}
});
};
the console.log seen above prints:
New_User {display_name: "test", email: "test#test.com", password: "Passw0rd"}
The server route is:
app.post('/user', (req, res)=>{
let body = _.pick(req.body, ['display_name', 'email', 'password']);
let user = new User(body);
user.save().then(()=>{
return user.generateAuthToken();
}).then((token)=>{
res.header('x-auth', token).send(user);
}).catch((err)=>{
res.status(400).send(err);
});
});
This route works when pinged with Postman. The server supports cors.
The model is as follows:
var UserSchema = new mongoose.Schema({
display_name: {
type: String,
unique: true,
required: true,
validate: {
validator: (val)=>{
return /^[\w\s]+$/.test(val);
},
message: '{VALUE} is not a valid display name. Only
alphanumeric, upper and lower case characters are allowed.'
}
},
email: {
type: String,
required: true,
unique: true,
validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email.'
}
},
password: {
type: String,
require: true,
minlength: 6
},
tokens: [{
access:{
type: String,
required: true
},
token: {
type: String,
required: true
}
}]
});
I'm still learning node.js. I was guided through the creation of the API, and am trying to build a front end on my own.
The object leaving contains the three value pairs - but the object arriving, before the server changes it, is empty. I'm at loss as to why.
SOLUTION: the problem was in the server-side bodyParser. I had forgotten to include the encoded url method. It was not parsing the JSON as it came in, since previously the API had only been tested using Postman there was no need to use the .urlencoded() method.

JQuery adds a comma when sending a variable to the server

I am using the https://jqueryvalidation.org/ library for form validation. When passing a variable to the controller, a comma is added to the beginning of the string. I do not know why.
Validation code
$('#registrationForm').validate({
rules: {
username: {
nowhitespace: true,
required: true,
minlength: 6,
maxlength: 36,
remote : {
url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
type: "GET",
data: {
username: function() {
return $('#username').val();
}
}
}
},
And this is my controller
#GetMapping("/checkUsername")
public boolean checkUsername(#RequestParam("username") String username) {
System.out.println("User: " + username);
return !userService.existsByUsername(username);
}
In addition to checking what happens, I added a username display and when passing the username to the controller the result is the following
User: ,j
User: ,jo
User: ,jon
User: ,jonk
User: ,jonki
I did not enter this comma. He added himself at the beginning. Appears out of nowhere.
Why have you appended username to url part as well as data field in post data. It is a get request. Do not use post data in that scenario.
You need to remove from your validate code
data: {
username: function() {
return $('#username').val();
}
}
Your final code should be
$('#registrationForm').validate({
rules: {
username: {
nowhitespace: true,
required: true,
minlength: 6,
maxlength: 36,
remote : {
url: '/checkUsername?username=' + encodeURIComponent($('#username').val()),
type: "GET"
}
},
Or you could try :
remote : {
url: '/checkUsername',
type: "GET",
data: {
username: function() {
return $('#username').val();
}
}
}

using ajax with javascript to put in database

I'm trying to put the infos into my database, for that, this code is in the connexion.jsp which is a page that ask to log with facebook.
the code is supposed to be called into the Controller which is a file in java, and go into the databse.
So my problem is the fact that the code $.ajax doesn't seems to work. It doesn't give a success or error window.alert with or without function(){}.
I might have missed some information about ajax, but i can't find more info about my error.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
} else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
You have a syntax error in front of your else.

Categories

Resources