Login / Logout

Login by username/password:

import org.apache.shiro.authc.*
import ch.insign.playauth.PlayAuth;
 
UsernamePasswordToken token = new UsernamePasswordToken("username", "secretword")
token.setRememberMe(true);
 
try {
    PlayAuth.login(token);
} catch (UnknownAccountException e) {
    // username wasn't in the system.
} catch (IncorrectCredentialsException e) {
    // password didn't match.
} catch (LockedAccountException e) {
    // account for that username is locked - can't login.
} catch (ExpiredCredentialsException e) {
    // credentials expired.
} catch (AuthenticationException e) {
    // unexpected condition - error?
}

Login manually:

Party p = PlayAuth.getPartyManager().findOneByPrincipal("username@example.com");
PlayAuth.authenticate(p);

Restore remembered authentication:

if (PlayAuth.isRemembered()) {
  PlayAuth.getPartyIdentifier() // Optional<String>
      .map(id -> PlayAuth.getPartyManager().find(id)) // Optional<Party>
      .ifPresent(PlayAuth::authenticate);
}

Logout:

if (PlayAuth.isAuthenticated()) {
    PlayAuth.logout();
}

 

Impersonation

Impersonation is similar to authentication except that Play Auth retains information about the original (previous) party and allows to return back to the original authentication. Only authenticated party can impersonate another party.

Party john = PlayAuth.getPartyManager().findOneByPrincipal("john@example.com");
Party bob = PlayAuth.getPartyManager().findOneByPrincipal("bob@example.com");
PlayAuth.authenticate(john);
 
println(PlayAuth.getCurrentParty().getName()); // prints "john"
 
if (PlayAuth.isAuthenticated()) {
    PlayAuth.impersonate(bob);
}
 
println(PlayAuth.getCurrentParty().getName()); // prints "bob"
 
if (PlayAuth.isImpersonated()) {
    println(PlayAuth.getPreviousParty().getName()); // prints "john"
    PlayAuth.endImpersonation();
}
 
println(PlayAuth.getCurrentParty().getName()); // prints "john"

 

 

Execute Code as Another Party

Sometimes it is usefull to execute a piece of code as another party, e.g. in unit tests, scheduled jobs, etc.

final Party john = ...;
 
// to enable JPA inside the code block use PlayAuth.executeWithTransactionAs
boolean itWorks = PlayAuth.executeAs(john, () -> {
    if (PlayAuth.getCurrentParty().equals(john)) {
        return true;
    } else {
        return false;
    }
});
 
assertTrue(itWorks); // this should never fail