Spring Security Users With Same Name - spring-security

If two users have same username in the database then how can spring security handle that?
I have two users with following login CREDENTIALS in database:-
1.Username:rohit password:1234
2.Username:rohit password:123

That means the user cannot be unique identified by the username only. So you have to think about the business requirements how to unique identify an user based on the information collected from the user request.
Enforcing the username to be unique across the system can definitely solve the problem. Ask the product owner if it is okay to do it .If not , ask him how to handle such case from the business 's point of view. Then based on the actual requirements of how to unique identify an user , you may need to customise the following classes (Assuming you are using the default username and password login form and authenticate against the user records from DB using JDBC) :
UsernamePasswordAuthenticationFilter
DaoAuthenticationProvider
UserDetailsService

Related

Asp.net Identity 2.0 - Add in memory role to user

I'm designing a system, where the admin will be able to login as a user to fix things on their behalf etc. I'd like it so they have an additional role during this period. Is there any way to add the role in memory or in a way that ends when they logout/close the browser. I could add the role from the admin screen and remove when that user logs in again but it could easily go wrong. Cheers.
This isn't about how to do impersonation. I've got that part working. I'd like to be able to add an additional role to the user but only when they are being impersonated (so there are a few extra diagnostic screens available). I think the person below is answering my question by explaining that when I add a claim, I'm adding it to the the cookie. I was thinking adding this information persisted back to the database. I will try that code tomorrow but I suspect it is the direction I need to go in. This is silly question but have the rules changed recently, I've noticed tonight people being a little enthusiastic to correct grammar etc.
ASP.NET Core 2.0 Identity uses claims based authentication. Each role is a claim. Claims are persisted for the session via several means but generally in the application cookie issued when they log in or JWT auth tokens (not in memory).
Using the SignInManager creating a user principal and adding an extra claim should be pretty trivial:
// create the user principal
var principal = await signInManager.CreateUserPrincipalAsync(user);
// add the extra role
principal.Identities.First().AddClaim(new Claim(ClaimTypes.Role, SomeRole));
// issue the application cookie
await HttpContext.SignInAsync(principal)

Using Spring Security authorization with context-specific authorities

We need to add access control to our application, making sure that every command is performed by a user who has the proper authorities for the given domain objects. We are already using Spring Security 4.0 for authentication and intend to use it for authorization as well.
What makes this complex is the way that authorities are granted to a given user. In our problem space, a User can found several Companies and hire other Users, making them Employees. Each User can be an Employee of several Companies. Some authorities can be granted to a User directly (e.g. canResetOtherUserPassword); other authorities can also be granted by a Company to an Employee based on their Role in the Company (e.g. canOpenProject, canRenameProject). When performing Company-independent commands, User-specific authorities must be checked by the service layer. When performing Company-specific commands (e.g. open a project for a company, rename an existing project), Employee-specific authorities must be checked.
Now let's consider these last two commands, which would have the following service signatures:
long openProject(long companyId, String title)
void renameProject(long projectId, String title)
To control access for the 1st method, the authorization component could retrieve the acting User through the thread-local SecurityContext.authentication, retrieve the Company using the companyId parameter, retrieve the Employee corresponding to the current User, then match Employee-specific authorities against the required canOpenProject authority.
To control access for the 2nd method, the authorization component could again retrieve the acting User through the Thread-local SecurityContext.authentication, retrieve the Project using the projectId, retrieve the owner Company through project.ownerCompanyId, retrieve the Employee corresponding to the current User, then match Employee-specific authorities against the required canRenameProject.
Clearly, this can be done using procedural code, as I just described. We would prefer to use a declarative approach similar to the #PreAuthorize interceptor that Spring Security already offers, and obviously to write as little code as possible. We just don't know where to start.
Any ideas?
Thanks in advance!
You can implement UserDetails (org.springframework.security.core.userdetails.UserDetails) or just extend a default implementation of UserDetails, like User (org.springframework.security.core.userdetails.User) ---> CustomUserDetails with additional attributes like company (with getters).
finally : use simply #PreAuthorize("principal.company.companyId == #companyId")
Reference : Spring Security 3.1 chapter 10 (you need to go back to chapter 3 for UserDetails implementation)
It was very useful for me !

reauthenticating users after promote them

Hi have an app in Spring mvc 3 and Spring Security 3. Happens that i decide promote an user( I have a database with user,role and user_role tables), but when i add the new role to database comes the problem, how updating the principal authorities without logout the user? Looking for an answer i found this:
// update database with new role
//... you fill in this part
// update the current Authentication
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority> (auth.getAuthorities());
authorities.add(new GrantedAuthorityImpl('ROLE_NEWROLE'));
Authentication newAuth = new UsernamePasswordToken(auth.getPrincipal(),auth.getCredentials(),authorities)
SecurityContextHolder.getContext().setAuthentication(newAuth);
Now, this approach looks good, but my question is, given that securitycontextholder retrieves the information concerned to the current user which calls him, how can I apply the code of above to each user in the system, from my admin account?
I am using my own authentication provider.
One option would be to implement the following strategy:
Keep a global registry of users whose roles have been modified. This could be implemented using a ConcurrentHashMap (or a distributed cache if you have multiple app servers).
As soon as an admin changes the role of a user, push the user's (whose role has been changed) principal (email address, username, etc.) to this registry.
Write a filter that checks whether the current user's principal in the registry. If the principal is in the registry, the filter refreshes the user's role and then removes the principal from the registry. The rest of the request is then handled as usual.

How to handle dynamic roles changing in Spring security?

Suppose in one application we have interface(UI) to assign roles.
First scenario:
So to say user A who is normal user. And one admin assigns him ADMIN role using UI.
Now when user A logins the application then he can see all the tabs which can be accessed by ADMIN.
Second scenario:
In the same time (when he is logged in and have session with ADMIN role), admin makes user A as normal USER who have normal privileges.
But as he is login as ADMIN so he can access all the admin information for all the tabs as in this session he has ADMIN role.
How I can solve this problem??
The first approach would be to expire any existing user sessions on the on the fly.
the following post describes two alternatives Is it possible to invalidate a spring security session?
A more sophisticated approach would be to flag the use in a list when his authorities changes.
Here is a good example Implementation of singleton thread-safe list
Furthermore, if you add a custom spring security filter which checks if the user is in the list and if necessary reauthenticates the user. I would use the switchuserfilter as a reference implementation. Instead of switching a user, you create a new authentication object and update the SecurityContextHolder.
All the necessary logic should be included in http://docs.spring.io/autorepo/docs/spring-security/3.0.x/apidocs/org/springframework/security/web/authentication/switchuser/SwitchUserFilter.html

Spring webapp security based on owner of record

Let's say I have users and articles.
Anonymous can list and read articles.
Only registered and logged user can create articles.
User can edit only own articles.
And, of course, admin can do anything.
I've looked at spring security, but didn't found a way to do that. My app don't need roles, and ACL will be too "heavy" for that.
Maybe I should implement my own security?
You're right, ACL would be too much for the task.
You can use Spring Security's authorize tag in JSP, which provides access to the logged in user via the principal object. Example to limit access to editing an article to the user with a given username:
<sec:authorize access="hasRole('SOME_PRIVILEGE_OR_ROLE') and ${someArticle.username} == principal.username">
...
</sec:authorize>
Note that SOME_PRIVILEGE_OR_ROLE could be some role like 'LOGGED_IN_USER', but could also rather specify a certain privilege, e.g. 'READ_ARTICLE' or 'UPDATE_ARTICLE'. Spring Security is flexible here. Whatever you choose, it needs to be in the GrantedAuthorities collection of your user object.
Note also that you can implement your own user object, adding further info to what the UserDetails interface provides, e.g. comparing the user's id rather than the username.
Finally, note that you need a recent version of Spring Security (>=3.1) for the Spring EL to work as in the example.

Resources