i am new in apache shiro.i am getting exception when i execute this statement.
currentUser.login(token);
exception is
errororg.apache.shiro.authc.AuthenticationException: Authentication failed for token submission [org.apache.shiro.authc.UsernamePasswordToken - abc#gmail.com, rememberMe=true]. Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).
i am invoking this method for login.the code is.
public boolean authorize(String username,String password)
{
Boolean status=false;
log.debug("the user id "+username+"passwrodD::"+password);
Realm realm = new JdbcRealm();
DefaultSecurityManager securityManager = new DefaultSecurityManager(realm);
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
token.setRememberMe(true);
SecurityUtils.setSecurityManager(securityManager);
Subject currentUser = SecurityUtils.getSubject();
Response r = null;
log.debug("before process for login");
try
{
currentUser.login(token); //This throws an error upon form submission
r = Response.ok().entity(token).build();
}
catch (UnknownAccountException uae ) {
//username wasn't in the system, show them an error message?
System.out.println("the user name is invalid");
} catch ( IncorrectCredentialsException ice ) {
//password didn't match, try again?
System.out.println("the password name is invalid");
} catch ( LockedAccountException lae ) {
//account for that username is locked - can't login. Show them a message?
} catch ( AuthenticationException ae ) {
//unexpected condition - error?
System.out.println("unexpect error"+ae);
}
return status;
}
my shiro.ini file
[main]
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery =select User_Password FROM user_master where User_id=?
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.serverName = localhost
ds.user = root
ds.password = root
ds.databaseName = test
jdbcRealm.dataSource = $ds
[users]
[roles]
[urls]
i include listener and filter in my web.xml file.
i change the authenticationQuery to my query. and when i am executing i am getting this above error. and also i do know is it right way to modify or override query.
I think the problem is that you are missing securityManager.realm = $jdbcRealm in your shiro.ini
I just got this exception, and the problem was I was setting securityManager.realm incorrectly in shiro.ini. This is what I had:
[main]
fooRealm = com.company.foo.Realm
securityManager.realms = fooRealm
This is what fixed it (I was missing a $):
[main]
fooRealm = com.company.foo.Realm
securityManager.realms = $fooRealm
Related
i'm developing for the first time using AWS Cognito in Java.
I created a code for an Admin to create a User. The user will be automatically created with the status FORCE_CHANGE_PASSWORD. What i was going to do now is a simple login, but if the system return a CHANGE_PASSWORD challenge, then it will open another window where the user should input old password and new password, then submit them to cognito.
The code i used to create a user through AdminCreateUser is the following:
// Creating instance of client CognitoIdentityProvider
CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder().region(Region.EU_CENTRAL_1).build();
AdminCreateUserRequest requestUserCreation = AdminCreateUserRequest.builder()
.username(usernameTextField.getText())
.desiredDeliveryMediums(DeliveryMediumType.EMAIL)
.userAttributes(AttributeType.builder()
.name("email")
.value(emailTextField.getText())
.build())
.userPoolId("xxxxx")
.build();
// Sending sign up request
AdminCreateUserResponse responseUserCreation = cognitoClient.adminCreateUser(requestUserCreation);
// Saving the group we want to put the user in through a combobox
String groupname = (String) groupComboBox.getValue();
UserType newUser = responseUserCreation.user();
GroupType group = GroupType.builder().groupName(groupname).build();
AdminAddUserToGroupRequest addUserToGroupRequest = AdminAddUserToGroupRequest.builder()
.userPoolId("xxxxx")
.username(newUser.username())
.groupName(groupname)
.build();
AdminAddUserToGroupResponse addUserToGroupResult = cognitoClient.adminAddUserToGroup(addUserToGroupRequest);
This code works. When i submit this through a button, an email arrives to the user i created, and it also shows in my Amazon Cognito console.
Now the login part is giving me trouble.
As i said, i want to open another windows which has the right form for resetting the password. I still haven't thought about the implementation for resetting the password because my login doesnt' work, so i will implement this later.
This is my login code:
public void Login(ActionEvent event) {
final String CLIENT_ID = cs.getAppClientId();
final String USER_NAME = userNameTextField.getText();
final String PASSWORD = passwordTextField.getText();
final Region region = cs.getRegion();
CognitoIdentityProviderClient cognitoClient = CognitoIdentityProviderClient.builder()
.credentialsProvider(DefaultCredentialsProvider.create())
.region(region)
.build();
InitiateAuthRequest authRequest = InitiateAuthRequest.builder()
.clientId(CLIENT_ID)
.authFlow("USER_PASSWORD_AUTH")
.authParameters(createAuthParameters(USER_NAME, PASSWORD))
.build();
try {
InitiateAuthResponse authResult = cognitoClient.initiateAuth(authRequest);
if (authResult.challengeName() != null) {
if (authResult.challengeName().equals(ChallengeNameType.NEW_PASSWORD_REQUIRED.toString())) {
try {
reimpostaPassword.apriSchermataReimpostaPassword(event);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
// The authentication was successful
AuthenticationResultType authenticationResult = authResult.authenticationResult();
System.out.println("Access token: " + authenticationResult.accessToken());
}
}
} catch (NotAuthorizedException e) {
System.out.println("Incorrect username or password");
} catch (PasswordResetRequiredException e) {
System.out.println("Password reset is required for the user");
}
When i fill my form with the right username and password, it gives me this error:
Caused by: java.lang.NullPointerException: Cannot invoke "software.amazon.awssdk.services.cognitoidentityprovider.model.AuthenticationResultType.accessToken()" because "authenticationResult" is null
at com.example.ratatouille23/com.example.ratatouille23.Login.LoginController.Login(LoginController.java:101)
at com.example.ratatouille23/com.example.ratatouille23.Login.LoginController.clickPulsanteLogin(LoginController.java:66)
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
... 51 more
The line that gives me error is this:
System.out.println("Access token: " + authenticationResult.accessToken());
This is an odd behaviour, because this means that the 'if the challenge is new password required' control fails, so i'm a little stuck here.
Any help?
I am working on this use case now. To get a very similiar example working, I created a user pool with an App that lets me use these Authentication flows.
When I execute my AWS SDK for Java V2 code that uses identityProviderClient.adminInitiateAuth() - I successfully get an Access Token - as shown here.
WHen i speicfy an incorrect password, I get exception as expected.
Here is a Java code example. To run this Java code example, create a new user in the specified user pool with a temporary password. You will get back a challenge type value of NEW_PASSWORD_REQUIRED in the response.
You cannot read the access token. This code then changes the temporary password to a permanent password. Now the user can log in with the permanent password and you can read the access token.
public class GetAccessToken {
public static void main(String[]args) {
final String usage = "\n" +
"Usage:\n" +
" <clientId> <poolId> <username> <tempPassword> <permanentPassword>\n\n" +
"Where:\n" +
" clientId - The app client Id value that you can get from the AWS CDK script.\n\n" +
" poolId - The pool Id that has the user. \n\n" +
" username - The new user name with a temp password. \n\n" +
" tempPassword - The temp password. \n\n" +
" permanentPassword - The permanent password. \n\n" ;
if (args.length != 5) {
System.out.println(usage);
System.exit(1);
}
String clientId = args[0];
String poolId = args[1];
String username = args[2];
String tempPassword = args[3];
String permanentPassword = args[4];
CognitoIdentityProviderClient identityProviderClient = CognitoIdentityProviderClient.builder()
.region(Region.US_EAST_1)
.credentialsProvider(ProfileCredentialsProvider.create())
.build();
boolean wasLoggedIn = getToken(identityProviderClient, clientId, username, tempPassword, poolId);
if (wasLoggedIn)
System.out.println(username +" successfully authenticated");
else {
// Change the temp password to a permanent one and then call getToken() again. Now you will
// get access tokens.
changeTempPassword(identityProviderClient, username, permanentPassword, poolId);
getToken(identityProviderClient, clientId, username, permanentPassword, poolId);
System.out.println(username +" successfully authenticated");
}
}
public static boolean getToken(CognitoIdentityProviderClient identityProviderClient, String clientId, String username, String password, String poolId) {
final Map<String, String> authParams = new HashMap<>();
authParams.put("USERNAME", username);
authParams.put("PASSWORD", password);
AdminInitiateAuthRequest authRequest = AdminInitiateAuthRequest.builder()
.clientId(clientId)
.userPoolId(poolId)
.authParameters(authParams)
.authFlow(AuthFlowType.ADMIN_USER_PASSWORD_AUTH)
.build();
try {
// If you specify an incorrect username/password, an exception is thrown.
AdminInitiateAuthResponse response = identityProviderClient.adminInitiateAuth(authRequest);
// Get the Challenge type
if (response.challengeNameAsString() == null) {
System.out.println("Access Token Type : " + response.authenticationResult().tokenType());
System.out.println("Access Token : " + response.authenticationResult().accessToken());
return true;
} else if (response.challengeNameAsString().compareTo("NEW_PASSWORD_REQUIRED") == 0) {
System.out.println("The User must change their password. ");
}
} catch(CognitoIdentityProviderException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return false;
}
public static void changeTempPassword(CognitoIdentityProviderClient identityProviderClient, String username, String newPassword, String poolId){
try {
AdminSetUserPasswordRequest passwordRequest = AdminSetUserPasswordRequest.builder()
.username(username)
.userPoolId(poolId)
.password(newPassword)
.permanent(true)
.build();
identityProviderClient.adminSetUserPassword(passwordRequest);
System.out.println("The password was successfully changed");
} catch(CognitoIdentityProviderException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
}
}
SO the reason why you get this NULL Exception is because you need to set the permanent password for the user. If the challengeName=NEW_PASSWORD_REQUIRED, you cannot read the access token.
I built a web service application with Jersey Jax-RS web service api, and i added apache shiro security framework in it, I can login to system without problem with apache shiro framework but I want to get current user info from another page and I wrote a GET method for this purpose, but in the GET method I can't get session information from Apache Shiro it returns null, I present code information below, please help me to get session information in GET method.
This is login method and it works fine:
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public SonucModel loginDeneme(LoginModel loginmodel) throws ClassNotFoundException {
shiroUser.setUsername(loginmodel.getUsername());
shiroUser.setPassword(loginmodel.getPassword());
//sonuc=logindao.sonucDonder(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(shiroUser.getUsername(), shiroUser.getPassword());
subject.login(token);
// UsernamePasswordToken token = new UsernamePasswordToken(username, password);
String userName = token.getUsername();
System.out.println("userName:" + userName);
if(subject.hasRole("admin")) {
Session session = subject.getSession(true);
session.setAttribute(CURRENT_USER_KEY, "admin");
sonucmodel.setSonuc("admin");
return sonucmodel;
}
else if(subject.hasRole("kasiyer")) {
Session session = subject.getSession(true);
session.setAttribute(CURRENT_USER_KEY, "kasiyer");
/* String username = (String) session.getAttribute(CURRENT_USER_KEY);
System.out.println("Session: " + username);*/
sonucmodel.setSonuc("kasiyer");
Session session1 = subject.getSession(false);
if(session1!=null) {
String username = (String) session.getAttribute(CURRENT_USER_KEY);
System.out.println("Session: " + username);
}
else if(session1 == null) {
System.out.println("session boş");
}
return sonucmodel;
}
//System.out.println("Session: " + username);
return sonucmodel;
}
but, this GET method could not get the session information
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getUser() {
//Subject subject= SecurityUtils.getSubject();
Session session = subject.getSession(false);
String message;
if(session != null) {
message = "Current user: " + session.getAttribute(CURRENT_USER_KEY);
} else {
message = "No current user, no session created";
}
System.out.println(message);
return message;
}
and this is the shiro.ini file :
[main]
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.authenticationQuery = SELECT password FROM users where username = ?
jdbcRealm.userRolesQuery = select role from users where username=?
ds = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
ds.serverName = localhost
ds.user = root
ds.password = asd123123
ds.databaseName = marketdb
jdbcRealm.dataSource= $ds
authc.loginUrl = /giris.html
#authc.successUrl = /kasiyer/index.html
user.loginUrl = /giris.html
[urls]
/giris.html = authc
/logout = logout
/admin/** = user, roles[admin]
/kasiyer/** = user, roles[kasiyer]
I change shiro auth from native SQL to JPA and I have some quations.
I make for example this link and this link
but i have errors.
[2015-12-03 08:58:33,087] Artifact ear:ear exploded: Artifact is being deployed, please wait...
[2015-12-03 08:59:06,931] Artifact ear:ear exploded: Error during artifact deployment. See server log for details.
[2015-12-03 08:59:06,932] Artifact ear:ear exploded: java.io.IOException: com.sun.enterprise.admin.remote.RemoteFailureException: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: java.lang.NoClassDefFoundError: org/apache/commons/collections/FastHashMap. Please see server.log for more details.
I not understend how it work. I Create JpaAuthorizingRealm class:
public class JpaAuthorizingRealm extends AuthorizingRealm {
public static final String REALM_NAME = "MY_REALM";
public static final int HASH_ITERATIONS = 200;
#Override
protected AuthorizationInfo doGetAuthorizationInfo(final PrincipalCollection principals) {
Long userId = (Long) principals.fromRealm(getName()).iterator().next();
User user = ShiroDao.me().userById(userId);
if (user != null) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for (Role role : user.getRoles()) {
info.addRole(role.getRoleName());
for (Permission permition : user.getPermissions()) {
info.addStringPermission(permition.getPermission());
}
}
return info;
} else {
return null;
}
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(final AuthenticationToken authToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authToken;
User user = ShiroDao.me().userByname(token.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
} else {
return null;
}
}
#Override
#Inject
public void setCredentialsMatcher(final CredentialsMatcher credentialsMatcher) {
super.setCredentialsMatcher(credentialsMatcher);
}
}
And models User, Role and Permission. And in ini file i registered :
[main]
cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
securityManager.cacheManager = $cacheManager
# realms to be used
adRealm = myPackeg.CustomActiveDirectoryRealm
adRealm.url = ldap://myIP
noPassWordCredentialMatcher=myPackeg.CustomNoPassMatcher
userRealm=myPackeg.JpaAuthorizingRealm
userRealm.permissionsLookupEnabled=true
userRealm.credentialsMatcher=$noPassWordCredentialMatcher
authc.loginUrl = /login.xhtml
user.loginUrl = /login.xhtml
authc.successUrl = /index.xhtml?faces-redirect=true
roles.unauthorizedUrl = /error/ErrorInsufficientPrivileges.xhtml?faces-redirect=true
securityManager.realms= $adRealm, $customSecurityRealm
authcStrategy = org.apache.shiro.authc.pam.AllSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $authcStrategy
;multipleroles = myPackeg.MultipleRolesAuthorizationFilter
multipleroles = myPackeg.MultipleRolesAuthorizationFilter
[roles]
[urls]
/javax.faces.resource/** = anon
/error/ = anon
/login.xhtml = authc
/logout = logout
#/admin/ChangePassword.xhtml= authc, roles[user]
/admin/**= authc, roles[administrator]
/reports/qcforcc_report.xhtml= authc, roles[user]
/reports/**= authc, roles[administrator]
/** = authc, roles[user]
#/** = user, multipleroles["administrator", "user"]
And if i change JpaAuthorizingRealm extends AuthorizingRealm to JpaAuthorizingRealm extends JdbcRealm error not shows.
Maby somebode know how create shiro auth with JPA?
This seems to more like a linkage error than a problem with Shiro. The error means that your code (or code in Shiro library) cannot find FastHashMap class from commons-collections.
This is most probably because have more than a single version of commons-collections in your classpath (your application, app server, etc.). The problem might be that an older version of commons-collections is getting preference before the newer version, and that the older version does not include FastHashMap.
I have implemented shiro with jpa and you can find the source code at https://github.com/nmojir/rest-basic-auth.
Hello all I want to know can I redirect user to accessdeniedpage.jsp in shiro custom jdbcrealm
Here is my code....
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws HostUnauthorizedException,AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
String clientIP = upToken.getHost();
// Null username is invalid
if (username == null) {
throw new AccountException("Null usernames are not allowed by this realm.");
}
Connection conn = null;
AuthenticationInfo info = null;
try {
conn = dataSource.getConnection();
String password = getPasswordForUser(conn, username); // get userpassword
boolean ipFlag = getIPFlag(conn,username); // check whether users ip needs to be check i.e. get ipflag from users tbl, if true check user's ip else not
boolean ipMatched = checkIP(conn,username,clientIP,ipFlag); // returns if user's ip matched with ip stored in database..
if (password == null) {
throw new UnknownAccountException("No account found for user [" + username + "]");
}
if(ipMatched == false){
// how to redirect user to accessdeniedpage.jsp ?
}
info = buildAuthenticationInfo(username, password.toCharArray());
} catch (SQLException e) {
final String message = "There was a SQL error while authenticating user [" + username + "]";
if (log.isErrorEnabled()) {
log.error(message, e);
}
// Rethrow any SQL errors as an authentication exception
throw new AuthenticationException(message, e);
} finally {
JdbcUtils.closeConnection(conn);
}
return info;
}
I am checking users ip, if ip not found in database I want to redirect user to accessdenied page
Update shiro.ini
[main]
ds = org.apache.shiro.jndi.JndiObjectFactory
ds.requiredType = javax.sql.DataSource
ds.resourceName = jdbc/myDataSource
ds.resourceRef = true
jdbcRealm = com.java.realm.MyRealm
# password hashing specification
sha256Matcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
sha256Matcher.hashAlgorithmName = SHA-256
jdbcRealm.credentialsMatcher = $sha256Matcher
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = SELECT password FROM users WHERE username = ?
jdbcRealm.userRolesQuery = SELECT role_name FROM user_roles WHERE username = ?
jdbcRealm.permissionsQuery = SELECT roleper FROM roles_permissions WHERE role_name = ?
jdbcRealm.permissionsQueryIP = SELECT ip FROM user_ip_permissions WHERE username = ?
jdbcRealm.permissionsQueryCountry = SELECT countryname FROM country_permissions WHERE username = ?
jdbcRealm.defaultPageQuery = SELECT default_page FROM users WHERE username = ?
jdbcRealm.dataSource = $ds
jdbcRealm.authorizationCachingEnabled = false
# specify login page
authc.loginUrl = /login.jsp
# redirect after successful login
authc.successUrl = /home.jsp
# roles filter: redirect to error page if user does not have access rights
# perms filter: redirect to error page if user does not have permissions
roles.unauthorizedUrl = /accessdenied.jsp
perms.unauthorizedUrl = /accessdenied.jsp
# request parameter with login error information; if not present filter assumes 'shiroLoginFailure'
# authc.failureKeyAttribute = simpleShiroApplicationLoginFailure
[urls]
/login.jsp = authc
# only users with some roles are allowed to use role-specific pages
/admin/** = authc,perms[page:*]
/java/** = authc,perms[page:javadeveloperpage]
/php/** = authc,perms[page:phpdeveloperpage]
/ruby/** = authc,perms[page:rubydeveloperpage]
/deo/** = authc,perms[page:deopage]
# enable authc filter for all application pages
/ApacheShiroLogin/** = authc
Thanks & regards
Since you want to deny access, logically you need to to throw AuthorizationException and map it to your custom page in web.xml
if(ipMatched == false){
throw new AuthorizationException();
}
And in your web.xml
<error-page>
<exception-type>org.apache.shiro.authz.AuthorizationException</exception-type>
<location>/path/to/accessdeniedpage.jsp</location>
</error-page>
On a side note, throwing AuthenticationException would be logical only in case of authentication failures.
I'm using the Flickrj API to log into flickr. For READ only access its fine, but I can't seem to correctly auth when i need WRITE access to add tags to photos.
As i understand the basic auth flow
Get a frob
Pass that frob requesting WRITE access, this returns a URL.
Call the URL to recieve a flickr token
Use the token in all subsequent requests
My code currently is
Flickr f = new Flickr(properties.getProperty(APIKEY),properties.getProperty(SECRET),t);
System.out.println(f.toString());
// 1 get a frob
AuthInterface authInterface = f.getAuthInterface();
String frob = authInterface.getFrob();
System.out.println("first frob "+frob);
// 2 get a request URL
URL url = f.getAuthInterface().buildAuthenticationUrl(Permission.WRITE,frob);
System.out.println(url.toString());
// 3 call the auth URL
// 4 get token
f.getAuthInterface().getToken(frob);
As you can see - i'm stuck on step 3?
I found this code de.elmar_baumann.jpt.plugin.flickrupload.Authorization. After step 2 the trick is to have the java desktop app open a browser window and a dialog. Once the user has logged in via the browser, they click the dialog so step four can be called and the token retrieved.
public boolean authenticate() {
try {
Flickr flickr = new Flickr("xx", "yy", new REST());
Flickr.debugStream = false;
requestContext = RequestContext.getRequestContext();
authInterface = flickr.getAuthInterface();
frob = authInterface.getFrob();
token = properties.getProperty(KEY_TOKEN);
if (token == null) {
authenticateViaWebBrowser();
} else {
auth = new Auth();
auth.setToken(token);
}
requestContext.setAuth(auth);
authenticated = true;
return true;
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, Bundle.getString("Auth.Error"));
}
return false;
}
private void authenticateViaWebBrowser() throws Exception {
URL url = authInterface.buildAuthenticationUrl(Permission.DELETE, frob);
LargeMessagesDialog dlg = new LargeMessagesDialog(Bundle.getString("Auth.Info.GetToken.Browse", url.toExternalForm()));
dlg.setVisible(true);
Desktop.getDesktop().browse(url.toURI());
JOptionPane.showMessageDialog(null, Bundle.getString("Auth.Info.GetToken.Confirm"));
auth = authInterface.getToken(frob);
token = auth.getToken();
properties.setProperty(KEY_TOKEN, token);
}
I have a error, The code granted me no read permissions.. And I dont know why...
But otherwise I have a Frog and a Token.. And It works !!
// Step 1) Get Frob
AuthInterface ai = f.getAuthInterface();
String frob = ai.getFrob();
System.out.println("frob: "+frob); //--> It Works !!
// Step 2) URL With Permissions
URL uc = ai.buildAuthenticationUrl(Permission.READ, frob);
String request = uc.toExternalForm();
uc.openConnection();
// Step 3) Call URL
System.out.println(request);
URI uri = new URI(request);
Desktop desktop = null;
if (Desktop.isDesktopSupported())
{
desktop = Desktop.getDesktop();
}
if (desktop != null)
{
desktop.browse(uri); // Open Explorer to Confirm
}
// Sleep until accepted in the explorer. After Press enter in Console
BufferedReader infile = new BufferedReader ( new InputStreamReader (System.in) );
String line = infile.readLine();
// Step 4) Get a token
Auth atoken = ai.getToken(frob); // Get a Token with a frob
String stoken = atoken.getToken(); // Get a token like String
System.out.println("Token: "+stoken);
Auth au = ai.checkToken(stoken); // Check token
RequestContext.getRequestContext().setAuth(au);