how to obtain a list of all currently logged-in users (including rememberme cookies) in grails with spring security - authentication

I'm building a grails app that has the spring-security-core 1.2.7.3 plugin as well as spring-security-ui 0.2 plugin, and would like to obtain a list of ALL the users that are currently logged in (ie have a currently active session). Users can login either through a login controller (daoAuthenticationProvider) or automatically through a rememberMe cookie.
I have implemented the code below, using ConcurrentSessionControlStrategy to create a sessionRegistry:
in /conf/spring/resources.groovy:
import org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy
import org.springframework.security.web.session.ConcurrentSessionFilter
import org.springframework.security.core.session.SessionRegistryImpl
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy
beans = {
userDetailsService(lablore.MyUserDetailsService)
sessionRegistry(SessionRegistryImpl)
sessionAuthenticationStrategy(ConcurrentSessionControlStrategy, sessionRegistry) {
maximumSessions = -1
}
concurrentSessionFilter(ConcurrentSessionFilter){
sessionRegistry = sessionRegistry
expiredUrl = '/login/concurrentSession'
}
}
In /plugins/spring-security-core/conf/DefaultSecurityConfig.groovy
useHttpSessionEventPublisher = true
In the controller:
controller{
def sessionRegistry
action(){
def loggedInUsers = sessionRegistry.getAllPrincipals()
}
}
It works well for
-users that login through the login page
-users that logout through a 'logout' link
-users who's session expires
HOWEVER, it does NOT work for users that authenticate automatically with a rememberMe cookie. It doesn't see that they have a newly created session.
If I understand correctly, this is because the RememberMeAuthenticationFilter is 'further up' in the filter chain compared to the ConcurrentSessionFilter, which is the one running the sessionRegistry? Or, I messed something up with my configurations....
Any help on how to get this to work would be great !
Thanks!!

The ConcurrentSessionControlStrategy is deprecated,
Use the ConcurrentSessionControlAuthenticationStrategy instead
Alternatively,
You can implement the HttpSessionListener interface which has the sessionCreated(HttpSessionEvent event) and sessionDestroyed(HttpSessionEvent event) methods, But you have to add the class you used
Implementations of this interface are notified of changes to the list of active sessions in a web application. To receive notification events, the implementation class must be configured in the deployment descriptor for the web application.
You can either add the implementation class to your deployment descriptor like so(i.e you web.xml file)
<listener>
<listener-class>com.hazelcast.web.SessionListener</listener-class>
</listener>
or by using the WebXmlConfig plugin in grails
Your implementation class could look like below, see Online users with Spring Security also
class WebSessionListener implements HttpSessionListener{
sessionCreated(HttpSessionEvent se){
//Checked if user has logged in Here and keep record
HttpSession webSession = se.getSession();
}
sessionDestroyed(HttpSessionEvent se){
//Checked if user has logged in Here and keep record
HttpSession webSession = se.getSession();
}
}

Related

How to authenticate JavaFX client in JavaEE

I develop three-tier application with JavaFX on client side, JavaEE/Glassfish on server side and MySQL as a database management system. Also I used REST and JSON for transferring the data across network.
Now I try to configure an authentication using JavaEE security means. I use declarative approach with annotations in enterprise beans, I've already configured Glassfish file realm (add user/group) and glassfish-web.xml descriptor (add group-name and role tags). JavaEE tutorial say that If all of needed preparations done then when client attempt to get the protected resource Glassfish should ask client for a login/password pair. I understand how it work if it would be a web-client, but in my case it is a desktop JavaFX client and I don't understand how Glassfish ask client in desktop application. How to make authentication mechanism with JavaFX-Glassfish?
Update
Authentication window popup if I try to call servlet from browser (Chrome, IE) and authentication mechanism is able to work. But when I open JavaFX window I see nothing (white scene).
Here is the code of class (JavaFX WebView), which I unsuccessfully used to open login window:
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class WebViewSample extends Application {
private Scene scene;
#Override
public void start(Stage stage) {
// create the scene
stage.setTitle("Web View");
scene = new Scene(new Browser(), 750, 500, Color.web("#666970"));
stage.setScene(scene);
scene.getStylesheets().add("webviewsample/BrowserToolbar.css");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class Browser extends Region {
final WebView browser = new WebView();
final WebEngine webEngine = browser.getEngine();
public Browser() {
getStyleClass().add("browser");
webEngine.load("http://localhost:8080/ForthDynamicWebProject/FirstServlet");
getChildren().add(browser);
}
}
You should not use standard Java EE cookie authentication here because your client is desktop application.
You can use Token authentication solution. The below is a guide.
Login servlet: This servlet will verify userName and password. If verification is success, the servlet will return a token contains userId, roles, expires ... etc. You can use JWT (Json Web Token) format. Token will be generated/validated by server using a secret key.
Login scene - JavaFX: When login button pressed, the app will send login request to the login servlet. If login is success, the app will receive a token and save the token in a secret storage for later uses. In memory should be ok.
For subsequent HTTP requests (JavaFX): The app need to resend the token (via header etc). The server will validate the token BEFORE actual resource get invoked. If the validation is success, request is consider as authenticated. You can use JavaEE Filter to validate the token.

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

unauthorizedRedirect set to false, still redirecting

I'm writing some REST api for my cake 3.0 application, and I need to set $this->Auth->unauthorizedRedirect to false, as the manual says that this would prevent my application to redirect to login url for unauthorized requests.
http://api.cakephp.org/3.0/class-Cake.Auth.BasicAuthenticate.html
The problem is that I'm trying to set it in my Users controller, and it doesn't work:
class UsersController extends AppController {
public function initialize() {
parent::initialize();
$this->loadComponent('RequestHandler');
}
public function beforeFilter(Event $event) {
parent::beforeFilter($event);
$this->Auth->allow(['logout']);
// Change the authentication mode when using REST api
if(! $this->RequestHandler->accepts('html')) {
$this->Auth->unauthorizedRedirect = false;
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
}
}
}
This scripts works fine as detecting if a user is actually registered, but fails when I try to use wrong authentication data, showing the login form instead of throwing an error. What am I doing wrong?
Authentication and authorization are two different things
You are mixing up authentication and authorization, that's two different things. Logging in a user is authentication, testing whether a logged in user is allowed to access a specific action is authorization.
So the unauthorized redirect configuration applies to logged in users when accessing actions.
Handling unauthenticated requests
What you are looking for, ie throw an exception on unauthenticated requests, is done by the basic authentication adapter by default, so I assume that you actually aren't using this adapter!?
So if you are using a different adapter, this behavior is best implemented in either your controller where you are trying to identify the user
$user = $this->Auth->identify();
if (!$user) {
throw new ForbiddenException('Stop! Hammer time!');
} else {
$this->Auth->setUser($user);
}
or, in case you want the exception to be thrown for every controller, in a custom authentication adapters unauthorized() method, which is being invoked on unauthenticated requests before executing possible redirects. Quote from the docs:
Cookbook > Authentication > Handling Unauthenticated Requests
When an unauthenticated user tries to access a protected page first the unauthenticated() method of the last authenticator in the chain is called. The authenticate object can handle sending response or redirection by returning a response object, to indicate no further action is necessary. Due to this, the order in which you specify the authentication provider in authenticate config matters.
If authenticator returns null, AuthComponent redirects user to login action. [...]
Here's a simple example that extends the form authentication handler:
src/Auth/MyCustomAuthenticate.php
namespace App\Auth;
use Cake\Auth\FormAuthenticate;
use Cake\Network\Exception\ForbiddenException;
use Cake\Network\Request;
use Cake\Network\Response;
class MyCustomAuthenticate extends FormAuthenticate
{
public function unauthenticated(Request $request, Response $response)
{
if(!$request->accepts('text/html')) {
throw new ForbiddenException('Ah ah ah! You didn\'t say the magic word!');
}
}
}
Controller
$this->loadComponent('Auth', [
'authenticate' => [
'MyCustom'
]
]);
See also
Cookbook > Authentication > Creating Custom Authentication Objects
Cookbook > Authentication > Using Custom Authentication Objects

How do i use Behat with Mink and WebApiContext?

The project i'm working on has a api behind a login.
I'm using behat with mink to login:
Scenario: Login
Given I am on "/login/"
And I should see "Login"
When I fill in "_username" with "test"
And I fill in "_password" with "test"
And I press "_submit"
Then I should be on "/"
This works..
However, the login session is not stored whenever i want to do the following using the WebApiContext:
Scenario: Getting the list of pages
When I send a GET request to "/api/pages.json"
Then print response
I'm using both scenarios in the same feature. My FeatureContext class looks something like this:
class FeatureContext extends MinkContext
{
public function __construct(array $parameters)
{
$context = new WebApiContext($parameters['base_url']);
$context->getBrowser()->getClient()->setCookieJar(new \Buzz\Util\CookieJar());
$this->useContext('web', $context);
}
}
I added the cookiejar idea from this issue without success.. When i print the response i just see the HTML page from the login screen..
Does anyone have any idea if i'm going at this totally the wrong way or am i somewhat in the right direction?
I am successfully using the same method. I don't think there's a standard way of doing this. As far as you understand the cookie basics you should be able to implement the solution.
In a common scenario, a client sends an authentication request to the server with some credentials, the servers validates it, starts an authenticated session and sends back a cookie with that session id. All following requests contain that id, so the server can recognise the callee. A specific header can be used instead of the cookie, or a database can be used instead of the session, but the principle is the same and you can (relatively) easily simulate it with Mink.
/**
* Start a test session, set the authenticated user and set the client's cookie.
*
* #Given /^I am signed in$/
*/
signIn()
{
session_start();
$_SESSION['user'] = 'jos';
$this->getSession()->getDriver()->setCookie(session_name(), session_id());
session_commit();
}
The above step definition (Behat 3) is the basics of it, you manually create the authenticated session and set to the client it's id. That must be also what the other example illustrates.
PHP's sessions can be problematic when you start doing more complex things and there are a couple of big underwater rocks with this solution. If you want to run assertions from both perspectives (the client and the server) you might often need to have your sessions synced. This can be done by updating the cookie before all Mink steps and reloading the session after.
/**
* #beforeStep
* #param BeforeStepScope $scope
*/
public function synchroniseClientSession(BeforeStepScope $scope)
{
// Setup session id and Xdebug cookies to synchronise / enable both.
$driver = $this->getSession()->getDriver();
// Cookie must be set for a particular domain.
if ($driver instanceof Selenium2Driver && $driver->getCurrentUrl() === 'data:,') {
$driver->visit($this->getMinkParameter('base_url'));
}
// Also enables the debugging support.
$driver->setCookie(session_name(), session_id());
$driver->setCookie('XDEBUG_SESSION', 'PHPSTORM');
}
/**
* #afterStep
* #param AfterStepScope $scope
*/
public function synchroniseServerSession(AfterStepScope $scope)
{
$driver = $this->getSession()->getDriver();
// Only browser kit driver, only initiated requests, only not repeating requests.
if (!$driver instanceof BrowserKitDriver) {
return;
} elseif (($request = $driver->getClient()->getRequest()) === null) {
return;
} elseif ($request === self::$request) {
return;
}
// Your logic for reloading the session.
self::$request = $request;
}
The biggest problem I had was the session reloading. This might be due to my framework of choice, which I doubt. The very first code snippet has session_commit(), which saves and closes the session. In theory in the following step definitions you must be able to session_id(/* session id from the cookie… */); and session_start();, but in practice that didn't work and no session data was actually loaded from the file, though the session did start. To solve this I created a custom session manager with reload() method using session save handler.
Second problem is where you cannot simply close the session without either writing it or destroying it (the support is added in PHP 5.6) on which relies the reloading itself. I reinvented the wheel with a flag for the session manager which tells it whether to write or just to close it.
:)

Log the logins to the various applications that identityserver manages

We've got a lot of sites with common authentication by thinktecture identityserver v2.
Now we would like to have a log of the logins to the sites. We've got a custom IUserRepository where we could log a user login in, but how would we goahead and grab the site a user is loggin into?
And when we jump from one site to another - how could that be logged
In case there's no built in support for this, where is the best place to modify the code?
It seems like it could be done in the WSFederationController and in the Issue method I could get the realm based on the uri.
public ActionResult Issue()
{
Tracing.Start("WS-Federation endpoint.");
if (!ConfigurationRepository.WSFederation.Enabled && ConfigurationRepository.WSFederation.EnableAuthentication)
{
return new HttpNotFoundResult();
}
var message = WSFederationMessage.CreateFromUri(HttpContext.Request.Url);
// sign in
var signinMessage = message as SignInRequestMessage;
if (signinMessage != null)
{
// Is this a good place to log current user and the application the user is loggin into to db???
// or does Thinktecture have some build in functionaltiy for this?
return ProcessWSFederationSignIn(signinMessage, ClaimsPrincipal.Current);
}
Larsi