Extra authentication criteria - authentication

I'm trying to implement an extra authentication layer with the purpose of authenticating the user only if he has a certain status.
If the status is different, I want to show a custom login error (Your account has been suspended) and not authenticate the user at all, similar to what happens if the credentials are wrong, but with a different error message.
So far I've tried two options:
I've added a check within a listener that checks for an "InteractiveLoginEvent". Here I can check the user status and set a flash error message but I don't see what's the proper way to redirect back to the login page, since this event has no response method, other than using a header() call which I definitely want to avoid.
I implemented a custom voter, set the "access_decision_manager" startegy to "unanimous" and returned "ACCESS_DENIED" if the status is not allowing the user to authenticate. So far so good, the user cannot access the resources but I see he still gets authenticated. And I definitely don't want that.
I'm not for sure if I'm missing something or if I'm going in the wrong direction.

Since symfony 2 makes a clear difference between authentication and authorization seems that option 2) is related to authorization, so option 1) is more suitable.
So among the "InteractiveLoginEvent" listener I just added the proper check for the user status and by throwing the following exception I managed to implement my functionality as needed:
throw new AuthenticationException('suspend error message');
So the listener looks something like this:
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
if ($this->securityContext->isGranted('ROLE_CUSTOMROLE')) {
$user = $this->securityContext->getToken()->getUser();
// ... check for the user status here
throw new AuthenticationException('Your account has been suspended!');
}
}

Related

Session lost after redirect SAML: may be different webapps?

I am fairly new to webapps programming, so I thought of asking here.
I am implementing the SAML2 protocol in an open source app (namely OFBiz) but I am encountering a problem related to session loss after the protocol made its course.
I am following these steps to implement the protocol. Suppose ofbizwebsite.com is the URL of the site.
Installed a custom plugin named SAMLIntegration which exposes the ACS page and the logic for login. To my understanding, a plugin (gradle) is like an indipendent java project, which translates to a new set of resources for the application (the plugin enables, for example, to visit ofbizwebsite.com/SAMLIntegration and setup some resources).
Exposed the ACS page to ofbizwebsite.com/SAMLIntegration/control/acs, as well as metadata ofbizwebsite.com/SAMLIntegration/control/metadata.jsp
Created the logic for login. Basically, an entity called UserLogin is saved in the session and recovered by a "checker" to understand if an user is logged in. Suppose that this checker is a HTTP WebEvent handler which can be called by any resource requiring authentication.
Now, the problem. If redirect the user to a resource on SAMLIntegration (for example ofbizwebsite.com/SAMLIntegration/control/aview or any ofbizwebsite.com/SAMLIntegration/control/* by calling response.sendRedirect("aview")) check works and login is preserved. Visiting any resource (for example ofbizwebsite.com/aplugin/control/anotherview) by navigating the application does not preserve the session.
OFBiz use internally a mechanism for preserving the userLogin between webapps, by creating an HashMap between and UUID and a UserLogin object. The UUID is passed between two different resources, appending this key to each path (so ofbizwebsite.com/aplugin/control/anotherview?externalKey=THEEFFECTIVEUUID)
To my understanding, changing from ofbizwebsite.com/SAMLIntegration/control/* to ofbizwebsite.com/aplugin/control/* determine a session loss. So, my idea was to replace the UUID mechanism with SAML2. However, I do not know how to solve this problem.
In particular, I would like to execute a SAML request each time the checker function is executed. If I can't find the user in the session, a SAML request is fired. However, my problem is HOW to manage the response. Normally, I would redirect it to the acs ofbizwebsite.com/SAMLIntegration/control/acs. Doing so, however, does not allow me to handle the response in the checker function, as the control is passed to another servlet by an external request (the SAML response fired by the IdP). Should I provide a different acs for each different path? (so one for SAMLIntegration and one for aplugin?) And, even if this was the case, how can I return the control to the checker function which has invoked the SAML request?
Here you go for installing the Shibboleth HTTPD module: https://pad.nereide.fr/SAMLWithShibboleth
You also need this method somewhere in OFBiz (I recommend LoginWorker.java, but you can put it where you want). It allows to use the externalAuthId of the userLogin for authentication, with the uid returned by the sso:
public static String checkShibbolethRequestRemoteUserLogin(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Delegator delegator = dispatcher.getDelegator();
// make sure the user isn't already logged in
if (!LoginWorker.isUserLoggedIn(request)) {
String remoteUserId = (String) request.getAttribute("uid"); // This is the one which works, uid at Idp, remoteUserId here
if (UtilValidate.isNotEmpty(remoteUserId)) {
//we resolve if the user exist with externalAuthId
String userLoginId = null;
GenericValue userLogin;
try {
List<GenericValue> userLogins = delegator.findList("UserLogin",
EntityCondition.makeConditionMap("externalAuthId", remoteUserId, "enabled", "Y"),
null, null, null, true);
userLogin = userLogins.size() == 1 ? userLogins.get(0) : null;
} catch (GenericEntityException e) {
Debug.logError(e, module);
return "error";
}
if (userLogin != null) {
userLoginId = userLogin.getString("userLoginId");
}
//now try to log the user found
return LoginWorker.loginUserWithUserLoginId(request, response, userLoginId);
}
}
return "success";
}
You also need to have this method as an OFBiz preprocessor in the webapp controllers. I suggest to have a look at common-controller.xml.
Finally you need the configs that redirect to the SSO page if no session. That should do the job, at least it works for them...
Finally I recommend https://www.varonis.com/blog/what-is-saml in case of need.

Slack API remove bot from channel

I'd like to remove a slack bot from a channel using slack's API.
I've tried channels.kick but ofcourse, a bot is not a user so it can't be deleted that way. I haven't found any solutions so far on the interwet or on Slacks API documentation.
You are not correct. You can remove a bot user from a public channel or private channel using API methods just fine. I just tested it on a private channel to confirm.
So there must be another reason why this does not work for you. Please check if any of these reasons below apply to your case. Also, please provide the error message you are getting from the API, as that would greatly help to identify the reason.
Here are some potential reasons why kicking a bot user might not work for you:
wrong method: channels.kick only works for public channel, use groups.kick for private channels.
wrong token: bot tokens can not use the kick methods. You need to use a user access token to invoke that API method. (you would get the user_is_bot error)
trying to remove oneself: a user can not kick himself. (you would get the cant_kick_self error)
not using channel IDs: the kick methods require you to provide a channel ID, the name will not work. (you would get the channel_not_found error)
Based on your question I would assume you are getting the user_is_bot error, which let you to assume (incorrectly) that you can't kick a bot. In that case the solution would be to use a user token (not a bot token) to execute the method.

IBM Worklight 6.1.0.1, trouble with 2 adapters based authentication

I am facing to a trouble with 2 adapters based authentication. My app is agenda (hybrid app). All adapter's functions must be protected by security.
my app uses adapters based authentication, like written in samples on DeveloperWorks.
My first adapter (loginAdapter) is dedicated for login (beginning of the mobile app). I developed a handler (handlerLogin, mobile side) with methods isCustomResponse, handlechallenge, etc.. This adapter works.
This adapter allows to get a userId from login and password.
As soon as connected, the user can download his agenda. The mobile calls an other adapter based auth (calendarAdapter). I have an other handler (handlerCalendar) with methods (isCustomResponse, handlechallenge).
When the mobile calls the method getCalendarData (protected method, CalendarAdapter), the server detects that the user is not registered for this adapter, that is why the server send an error (structure authrequired + errorMessage) via the function onAuthRequired.
At this step, all works fine.
Actually, the trouble comes from, that, the first handler (handlerLogin) catches this error, whereas it schould be the second handler (handlerCalendar).
Given that it is catched by the handlerLogin, isCustomResponse and handlechallenge are called, and I do not have the expected result ! I do not know why.
Why it is not catched by the handlerCalendar ?
I verified my code, variable's names, files, etc.. All things are ok.
For informations, I first declared the handlerLogin before the CalendarLogin.
Do you have any ideas, suggestions ??
Thank you in advance
It looks like you used the same realm.
The isCustomResponse function job is to find out if this challenge-handler should take care of this specific request. If you use the same realm for both adapters then the 2 challenge-handlers will react to it.

CakePHP Authentication on REST API

So I'm creating a REST API for a web app I'm developing, and I know the basic ways for authentication are either sending the credentials on each request or sending a token.
Since I have never used token before, I think I may send the credentials for each request. The point is I can't find any examples on how to handle this in the controller. Would it be something like this?
public function api_index() {
if(!$this->Auth->login()) return;
$this->set(array(
'models' => $this->Model->find('all'),
'_serialize' => array('models')
));
}
I don't really think this is the way AuthComponent::login() works, can I get some directions here please?
Alright, first a clarification about how AuthComponent::login works. In Cake 2.x that method does not do any authentication, but rather creates the Auth.User array in your session. You need to implement the actual authentication yourself (the User model is a natural place to do this). A basic authentication method might look like this:
App::uses('AuthComponent', 'Controller/Component');
public function authenticate($data) {
$user = $this->find('first', array(
'conditions' => array('User.login' => $data['login']),
));
if($user['User']['password'] !== AuthComponent::password($data['password']) {
return false;
}
unset($user['User']['password']); // don't forget this part
return $user;
// the reason I return the user is so I can pass it to Authcomponent::login if desired
}
Now you can use this from any controller as long as the User model is loaded. You may be aware that you can load it by calling Controller::loadModel('User').
If you want to authenticate every request, then you should then put in the beforeFilter method of AppController:
public function beforeFilter() {
$this->loadModel('User');
if(!$this->User->authenticate($this->request->data)) {
throw new UnauthorizedException(__('You don\'t belong here.'));
}
}
All of the above assumes that you pass POST values for login and password every time. I think token authentication is definitely the better way to go, but for getting up and running this should work. Some downsides include sending password in cleartext (unless you require ssl) every request and the probably high cpu usage of the hashing algorithm each time. Nevertheless, I hope this gives you a better idea of how to do authentication with cakephp.
Let me know if something needs clarifying.
Update:
Since posting this, I found out that you can actually use AuthComponent::login with no parameters, but I am not a fan of doing so. From the CakePHP documentation:
In 2.x $this->Auth->login($this->request->data) will log the user in with
whatever data is posted, whereas in 1.3 $this->Auth->login($this->data)
would try to identify the user first and only log in when successful.
AuthComponent::login() creates a session variable that stores the user data, so say you had data that was something like.
$data = array('User' => array('id' => 1, 'username' => 'johndoe'));
Then you would use
$this->Auth->login($data);
And access the data with
$this->Auth->user('User');
To get the user id
$this->Auth->user('User.id');
In your AppControllers beforefilter put $this->Auth->deny(); that will deny all actions to someone who is not logged in. Then in each controllers before filter you want to $this->Auth->allow(array('view')); 'view' being the name of an action you want to be public.
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Cakephp 2.X, After lots of research about this on internet I did not find any satisfactory answer So I found a way myself to do this. May be this answer will help some folks in future. This answer is only applicable for REST API's in cake php.
Add following line in your logic action of REST API before checking for the $this->Auth->login().
$this->request->data['User'] = $this->request->data ;
if($this->Auth->login()){
echo "Hurray You are logged In from REST API.";
}
else
{
throw new UnauthorizedException(__('You don\'t belong here.'));
}
Desciption : As #threeve said in one of the answers that $this->Auth->login() does not do any authentication itself. but rather creates the Auth.User array in your session. For Authentication we require our $this->request->data to be inside User array since User is the model which will check the Credentials in Database. Therefore we have to pass the data to Auth as it is required when not using REST API's. Rest of the things will be handled by Cake and Auth itself.
Any enhancements or suggestions on this answer are most welcome.

RestKit how to check for wrong username or password error

I want to be able to notify the user if he entered the wrong username/password, or if for example the database is down. I am not sure if I need to do it in the didLoadResponse and just check that the response is not isOK or in the didFailLoadWithError.
Thanks
How you handle it depends on how you perform a login.
If you do basic authentication, by passing the username and password in the header of the request, then you'll get an error back from the service you're calling. And your delegate method, "objectLoader:didFailWithError:" method will get called. This method will most likely get called if there's a catastrophic problem on the backend, like the database being down.
If you have a separate webservice that performs a login operation, then it probably sends back a valid block, indicating whether the user-pass was valid or not. In this case, your "objectLoader:didLoadObject:" method probably got called, and you'll have to decipher the result appropriately.
Keep in mind that this behavior is totally controlled by what the back-end services do. If you can't talk directly with the people working on the services, then this may just be trial-and-error, and until you discover how those services work.