Liferay auto login - authentication

I must use Liferay 5.2.3 and tomcat-5.5.27
I have to login user programmatically.
I create a portlet and a file "view.jsp"
I found and tried this code:
String username = String.valueOf(user.getUserId());
String password = user.getPassword();
HttpSession session = request.getSession();
session.setAttribute("j_username", username);
session.setAttribute("j_password", password);
session.setAttribute("j_remoteuser", username);
I find the user by id but i'm not signed in liferay.
What am i missing?

Sorry but it's totally wrong way.
You need an hook plugin, have to implement an AutoLogin based class with a custom portal.properties to setup auto.login.hooks property.
Follow this discussion: https://community.liferay.com/it/forums/-/message_boards/message/114134

Related

Web-Shiro getSuccessUrl of PassThruAuthenticationFilter

I've used Shiro's inbuilt login behavior for sometime. The user is redirected to the login page when they try to access a protected resource, then after successful login, they are redirected back to the resource they were trying to access; that is, the successUrl property of PassThruAuthenticationFilter.
Now that I'm using my own custom login, I can't seem to find a way of getting this successUrl right. Below is shiro.ini configuration:
shiro.ini
[main]
authc = org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter
authc.loginUrl = /login.xhtml
authc.successUrl = /index.xhtml #index.xhtml is fallback url
Below is my login code
Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFileDir + "shiro.ini");
SecurityManager securityManager = factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
session = currentUser.getSession();
PassThruAuthenticationFilter filter = new PassThruAuthenticationFilter();
String url = filter.getSuccessUrl();
if (!currentUser.isAuthenticated()) {
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
//
//
//
}
I know it does not make sense to use getSuccessUrl on a newly initiated PassThruAuthenticationFilter class, so I'm wondering, what's the correct way of getting the filter object?
I eventually found the solution; I added the following lines in my login code:
import org.apache.shiro.web.util.WebUtils;
//...
String successUrl = WebUtils.getSavedRequest(request);
It worked like a charm. I din't have to worry about PassThruAuthenticationFilter anymore.
Updated
I found it from this link
Use the following from within your Spring MVC controller:
import org.apache.shiro.web.util.WebUtils; ... String fallbackUrl =
"/path/to/go/to/incase/there/is/no/saved/request";
WebUtils.redirectToSavedRequest(request, response, fallbackUrl);
return null; //tell Spring MVC not to render a view, we're redirecting
explicitly

How can I get a user password using the Auth0 Management API nuget package?

We are currently trying to make a change to our website so that it uses Auth0 to authenticate. As part of that, I am rewriting a "config" website that we have for managing the users. The users will now be stored in Auth0 and the config website will therefore have to be able to add and edit Auth0 users in my tenant.
The config website uses the Auth0 Management API nuget package: https://github.com/auth0/auth0.net
But I have run into a problem. I can get a list of users and I can create a user. I can get the user's details and present them in an edit form onscreen, but I can't save the changes made, because when I try to do this I get an error that I need to supply a password in the UserUpdateRequest.
But when I get the user's details (client.Users.GetAsync(id)), it doesn't give me back a password property. If I could get the password from the call to GetAsync(id) then I could add it to the UserUpdateRequest. But if I can't get the password from GetAsync, how can I put the password in the UserUpdateRequest? How am I supposed to ever save a user?
I guess my ultimate question is: how can I get the user's password using the Management API...so that I can supply it later on to the UserUpdateRequest model when calling Users.UpdateAsync. Or if I can't get the user's password, can I somehow update the user without knowing their password?
It looks like the Nuget Management API was expecting this method to be used by the user themselves (and they could therefore put in their password to change their details), not an admin user operating through a config/admin website that wouldn't know the users password.
C# User/Edit [HttpGet] action method to get users and display them:
var token = GetAccessToken();
var apiClient = new ManagementApiClient(token, new Uri("https://MY_TENANT_ID.au.auth0.com/api/v2"));
var user = await apiClient.Users.GetAsync(id);
var userModel = MapUserToUserModel(user);
return View(userModel);
C# User/Edit [HttpPost] action method to save the changes to user's details:
var token = GetAccessToken();
var apiClient = new ManagementApiClient(token, new Uri("https://MY_TENANT_ID.au.auth0.com/api/v2"));
var updateReq = new UserUpdateRequest()
{
UserName = model.UserId,
Email = model.Email,
Password = model.Password,
EmailVerified = model.EmailVerified,
AppMetadata = model.AppMetadata,
UserMetadata = model.UserMetadata
};
var user = await apiClient.Users.UpdateAsync(model.UserId, updateReq);

Store password in Keycloak

I have created a custom user storage provider which will migrate users from legacy system to keycloak's local storage on demand basis.
All the details of the migrated user is being stored in Keycloak except password.
userModel.setEmail(email);
userModel.setEnabled(isEnabled);
userModel.setEmailVerified(isEmailVerified);
userModel.setFirstName(firstName);
userModel.setLastName(lastName);
I am using the above code to store all the information of the user, but I didn't find any method/class in which stores the password.
Can anyone please help me with it?
P.S. I am using Keycloak-3.3.0-Final version.
You can use
session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password(passwordNew, false));
where session is the current KeycloakSession which you have access to in your custom user storage provider.
Thanks to Boomer's answer I managed to make it work in my implementation where the isValid function - which sends the POST request to validate the password - needed to trigger the update of password in Keycloak database.
#Override
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!supportsCredentialType(input.getType()) || !(input instanceof UserCredentialModel)) return false;
UserCredentialModel cred = (UserCredentialModel)input;
// sending a POST request
Response response = userService.validateLogin(user.getUsername(), new EventivalUserCredentialsDto(cred.getValue()));
boolean isValid = HttpStatus.SC_OK == response.getStatus();
if (isValid) {
// save the password to local (keycloak's native) database
session.userCredentialManager().updateCredential(realm, user, cred);
// unset the federation link to never ask again - Import Implementation Strategy
user.setFederationLink(null);
}
return isValid;
}

Apache Shiro - LDAP for Authentication and Properties/Ini for Authorization

i´m trying to add some authentication and authorization functionality to my small web application. therefore i´m using apache shiro.
my plan: using an existing ldap server for user authentication and using a properties or ini file for authorization.
here´s a small example:
user x wants to use the application
he enters his username and his password
the ldap server is used for authentication --> user + pwd correct?
if authentication is verified and correct, a properties file or ini file is used to check if the user is permitted, to start some functions inside the application.
i hope you know what i´m trying to do.
now i´m not sure how to implement this feature. is it enough to use an ini file or is it required to implement my own realm?! is there an example implementation?
i´m grateful for every information
and sorry for my bad english :/
Yes, you have to implement a realm but this is not difficult. You just have to extend JndiLdapRealm and override the queryForAuthorizationInfo method.
This method returns an AuthorizationInfo interface type. In your case the easiest is to return an instance of SimpleAuthorizationInfo which implements this interface.
You must initialize the AuthorizationInfo with the roles and/or permissions for the authenticated user. When this method is called, the user is already authenticated but not authorized.
Inside this method you can read the authorization information from any data source that you want, it can be a properties or ini file, properties associated with the user in the LDAP server, a database or anything that pleases you.
A realm implementation could be:
package example.shiro.realm.ldap;
import javax.naming.NamingException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.ldap.JndiLdapRealm;
import org.apache.shiro.realm.ldap.LdapContextFactory;
import org.apache.shiro.subject.PrincipalCollection;
public class JndiLdapAuthzRealm extends JndiLdapRealm {
private List<String> getRoles(String userName) {
List<String> roles = new ArrayList<>();
// TODO: get roles from data source and fill list
roles.add("user");
roles.add("admin");
return roles;
}
private List<String> getPermissions(String userName) {
List<String> perms = new ArrayList<>();
// TODO: get permissions from data source and fill list
perms.add("myapp:run");
perms.add("myapp:file:create");
return perms;
}
#Override
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals,
LdapContextFactory ldapContextFactory) throws NamingException {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
String userName = principals.getPrimaryPrincipal().toString();
info.addRoles(getRoles(userName));
info.addStringPermissions(getPermissions(userName));
return info;
}
}
In your case, rewrite the getRoles and getPermissions to get the roles and permissions for the authenticated user from the properties or ini file.
In shiro.ini:
[main]
ldapRealm = example.shiro.realm.ldap.JndiLdapAuthzRealm
ldapRealm.userDnTemplate = uid={0},cn=users,cn=accounts,dc=example,dc=com
ldapRealm.contextFactory.url = ldap://192.168.0.10

Symfony Security / Custom User Provider : How to get the login password within the custom User Provider?

I'm using Symfony Security with a custom User Provider in my system. It provide users via a web service.
I configure the provider according to this tutorial (http://symfony.com/doc/current/cookbook/security/custom_provider.html).
Here is the function which check the user:
public function loadUserByUsername($username)
{
$userData = webServiceCheckUser($username);
// return an array whit user credentials
if ($userData) {
$password = $userData['password'];
$salt = $userData['salt'];
$roles = $userData['roles'];
$user = new WebserviceUser($username, $password, $salt, $roles);
return $user;
}
throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
}
This works fine, the function webServiceCheckUser() call a web service with the username and then it return an array with user data. But now I need to check the user through another web service that requires the username and encrypted password of the user to authenticate him.
I have a function that encrypts the plain text password like the web service is waiting, but I can't get the password that was typed by the user in the form login within the custom user provider class. It is ok too if I could get the password already encrypted. Either one solve the problem.
There is anyway to do this?
#Pazi is correct in that building your own custom authentication provider will work. However, it's not an easy task.
An alternative approach is to override DaoAuthenticationProvider and have it pass the password to the loadUser function.
security_listeners.xml:
<parameter key="security.authentication.provider.dao.class">
Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider
</parameter>
Bit of a hack perhaps but it saves a good deal of work.