am new on Symfony2 and using fosuserbundle to manage my users
how do i access the user object from my controller. I need to get the user_id to build a directory which would look like this : uploads/{user_id}/...
You can access the user object in a controller this way:
$this->getUser();
So if you need the user id, you can use the getter method:
$this->getUser()->getId();
Related
I'm currently working on a fastify project, where I use fastify-jwt to create Bearer tokens to my users.
And in the routes I acces it with following:
fastify.get(
"/test",
{
preValidation: [fastify.authenticate],
},
Collection.functionX
);
So know I want some routes not accessible for "normal" users, only for "admin" users. Normally this information is within the token. I can grand access to only admins within the function, by I want to directly not give access to the route. So it directly calls "not allowed".
I found fastify Guard but it is not working.
you can use firebase authentication or any ,and put the user in a data base with a schema has property "role",then check this role in middleware,for example if role==0 its admin and so on .
I want to make Multiple role Access Project Where I have to allow user according to their roles , so for this I have to create multiple Middleware & Guard according to Roles but there is no documentation how to get current login user details inside Nest Middleware and also how to get current login user details from jsonWebToken inside Nest Guard & Middleware,
I have Users collection schema is Like that
UsersCollectionSchema: {
name: '',
email:'',
password:'',
roles: [ admin, editor]
}
Once the user has been authenticated, i suggest you to attach the user object to the request, it’s the common way, in order to have access to the user inside the middleware through the request and inside the guard through the request that you can get from the executionContext
Here is an example https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/common/guards/roles.guard.ts
I'm trying to understand something about Symfony and the "super admin".
When I use FOSUser to create a user with super admin privileges
php app/console fos:user:create adminuser --super-admin
I'd firstly like to know what means (from the doc)
[...]Specifying the --super-admin option will flag the user as a super admin[...]
I imagine it means granting ROLE_SUPER_ADMIN to the user because I don't see any super-admin field in the user table.
Secondly, while (still from the doc)
A super admin has access to any part of your application
security:
role_hierarchy:
ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH, ...]
Why do we still need to configure the access hierarchy for it ?
Looking at FOSUserBundle's code you will find that the CreateUserCommand if invoked with the --super-admin flag will call the UserManipulator with a boolean argument $superadmin=true.
Now the UserManipulator calls the UserManager who will create a User Object, call it's setSuperAdmin() method and persist the new user afterwards.
The method looks as follows:
public function setSuperAdmin($boolean)
{
if (true === $boolean) {
$this->addRole(static::ROLE_SUPER_ADMIN);
} else {
$this->removeRole(static::ROLE_SUPER_ADMIN);
}
return $this;
}
So answering your first question:
Yes, the --super-admin flag causes FOSUserBundle to create a new user with the ROLE_SUPER_ADMIN role.
You still have to include the role hierarchy in your security configuration because the ROLE_SUPER_ADMIN role basically doesn't differ from any other role.
It's just a convention provided by the Symfony standard edition that users with role ROLE_SUPER_ADMIN should not have any access restrictions.
If you want the ROLE_SUPER_ADMIN to bypass all security voters by default - have a look at JMSSecurityExtraBundle's IddqdVoter which implements this for the special role ROLE_IDDQD. But this has already been suggested in your other question here.
By defining the hierarchy, you explicitly grant it the ROLE_ADMIN and ROLE_ALLOWED_TO_SWITCH roles (or other custom roles you could have)
If you comment this line, and you try to access with your ROLE_SUPER_ADMIN user to an action with a ROLE_ADMIN check, you will get a not allowed error.
The ROLE_SUPER_ADMIN is just a convention for the name the super administrator role should have, but it does not have privileges by it's own, you have to explicitly grant them to it.
I am using a solution similar to http://blog.jmoz.co.uk/symfony2-fosuserbundle-role-entities
So I have a Role entity that implements RoleInterface and I have a modified User entity that is set up to have a ManyToMany relationship with the Roles.
This allows me to use code like this
$user = $this->get('security.context')->getToken()->getUser();
$role = new Role('ROLE_TEST');
$user->addRole($role);
$em = $this->getDoctrine()->getEntityManager();
$em->persist($role);
$em->persist($user);
$em->flush();
I can then check if a user has a role with
$user = $this->get('security.context')->getToken()->getUser();
if($user->hasRole('ROLE_TEST')){
//do stuff...
}
This solution is ok, but I need to have access to the security context and use code like this:
if($this->get('security.context')->isGranted('ROLE_TEST')){
//do stuff...
}
And in the security.yml cofig file I would like to use the access_control code like this:
access_control:
- { path: ^/test$, role: ROLE_TEST }
Do I need a custom user manager for this? The roles that are assigned to a user in the database are not being carried over to the built in Symfony security system.
In other words when I view the security section of the profiler it shows that the user is assigned to Roles [ROLE_USER], but I am hoping to get it so the system will also recognize the roles that I have set in the database for the logged in user such as ROLE_TEST.
The reason that this was not working is because I was still logged in with the same session. Logging out and then back in again to refresh the session with the new roles does the trick. DOH!
I have succesfully created a REST web service with Jersey and secured it via java security annotations.
It looks something like this
GET /users/ // gives me all users
GET /users/{id} // gives the user identified by {id}
POST /users/ // creates user
PUT /users/{id} // updates user identified by {id}
DELETE /users/{id} // delete user
I also have setup a realm with two roles: user and admin
I secured all methods so that only admins can access them.
Now i want to give free the PUT /users/{id} and GET /users/{id} methods, so that users can access their own and only their own resources.
Example:
// user anna is logged in and uses the following methods
GET /users/anna // returns 200 OK
GET /users/pete // returns 401 UNAUTHORIZED
Since i could not find a way to configure this through annotations, I am thinking of passing the HTTP request to the corresponding method to check if the user is allowed to access the resource.
It would look something like this for the GET /users/{id} method:
#GET
#Path("/users/{id}")
#RolesAllowed({"admin","user"})
#Produces(MediaType.APPLICATION_JSON)
public Response getUser(
#PathParam("id") String id,
#Context HttpServletRequest req
) {
HttpSession session = request.getSession(false);
if (session != null && session.getValue("userID").equals(id))
return getObject(User.class, id);
return Response.status(Status.UNAUTHORIZED).build();
}
I don't like this aproach because i think i would have to add the userID manualy to the session.
Do you know a more elegant way to solve this?
If not how do you add the userid to the session while using form authentication?
EDIT
Thank you Will and Pavel :) Here is my final solution:
#Context
private SecurityContext security;
// ...
#GET
#Path("/users/{id}")
#RolesAllowed({"admin","user"})
#Produces(MediaType.APPLICATION_JSON)
public Response getUser(#PathParam("id") String id){
if (security.isUserInRole("user"))
if (security.getUserPrincipal().getName().equals(id))
return getObject(User.class, id);
else
return Response.status(Status.UNAUTHORIZED).build();
else
return getObject(User.class, id);
}
In the HttpServletRequest, you can call getRemoteUser() or getUserPrincipal() to get the identity of the logged in user. You would then continue like you are doing in specifically allowing or denying them access to the particular resource.
Blessed Geek is referring more specifically to the aspect of REST regarding stateless transactions and the use of HTTP authentication. While this is an important point in the larger scope of a REST architecture, it's less relevant to your specific question since you don't specify the type of authentication mechanism you're using against your Java EE app, especially since authentication is a container issue in Java EE, not an application issue.
If you're using basic authentication, then you are using HTTP headers to manage authentication and authorization. If you're using form based authentication, then the container is managing this for you via the servlet session, making the service stateful (since sessions are a stateful artifact).
But this has no bearing on your specific question.
One of the most important aspects of deploying REST is understanding the role of http headers and cookies.
For REST to be practical, you need to deploy an authentication framework.
Read
GWT and Google Docs API.
GWT-Platform login + session management
Read up on Google Federated Login, OAuth and OpenID.
Some of my explanations may be outdated, if they were posted before OAuth 2.0.