OpenAM Authentication - logout - java

I'm beginner with OpenAM, I'm working on an existing project.
I use this documentation to improve our authentication service:
http://docs.forgerock.org/en/openam/10.0.0/dev-guide/index/chap-authentication.html
The login works fine, I receive my token Id and add it in the cookies. I stay connected when I browse restricted web pages.
Now I want to do a clean logout.
When you read the documentation about logout, they propose this code:
protected void logout(AuthContext lc)
throws AuthLoginException {
lc.logout();
System.out.println("Logged Out!!");
}
But in my program, I do not have the login AuthContext anymore.
Is there a way to get or create an AuthContext associated with my user ? This call is it necessary ? (actually, We modify the cookies to be rejected by OpenAM)
Thank you.
Answer:
SSOToken ssoToken = SSOTokenManager.getInstance().createSSOToken(tokenId);
AuthContext authContext = new AuthContext(ssoToken);
authContext.logout();

Firstly I think you should be able to create a new AuthContext by having access to the session token, by using this constructor.
Secondly it is not necessary to use the ClientSDK to perform authentication remotely, you could also just use the REST APIs, which probably would be a bit more lightweight.

Related

In Vertx - how to make a callback?

I have a problem with Vertx oauth2.
I followed this tutorial http://vertx.io/docs/vertx-web/java/#_oauth2authhandler_handler:
OAuth2Auth authProvider = OAuth2Auth.create(vertx, OAuth2FlowType.AUTH_CODE, new OAuth2ClientOptions()
.setClientID("CLIENT_ID")
.setClientSecret("CLIENT_SECRET")
.setSite("https://github.com/login")
.setTokenPath("/oauth/access_token")
.setAuthorizationPath("/oauth/authorize"));
// create a oauth2 handler on our domain: "http://localhost:8080"
OAuth2AuthHandler oauth2 = OAuth2AuthHandler.create(authProvider, "http://localhost:8080");
// setup the callback handler for receiving the GitHub callback
oauth2.setupCallback(router.get("/callback"));
// protect everything under /protected
router.route("/protected/*").handler(oauth2);
// mount some handler under the protected zone
router.route("/protected/somepage").handler(rc -> {
rc.response().end("Welcome to the protected resource!");
});
// welcome page
router.get("/").handler(ctx -> {
ctx.response().putHeader("content-type", "text/html").end("Hello<br>Protected by Github");
});
The ideas is to have in the protected folder all the webpages that requires auth.
When I want to access to protected webpage I get redirected to the microsoft login site and after the login I get redirected to my callback.
What I donĀ“t understand is how to handle the callback now?
I get something like this as response:
https://localhost:8080/callback?code=AAABAAA...km1IgAA&session_state=....
How I understood (https://blog.mastykarz.nl/building-applications-office-365-apis-any-platform/) I need to extract somehow the code and the session-state and send back with a post to:
https://login.microsoftonline.com/common/oauth2/token
in order to get the token.
But I did not understand how this can be done with Vertx.
Any help? How to extract the code and session and send back to Microsoft?
I found some tutorials here: https://github.com/vert-x3/vertx-auth/blob/master/vertx-auth-oauth2/src/main/java/examples/AuthOAuth2Examples.java but did not help me.
I am doing this with Azure authentication (in tutorial is written Github but i changed all this to Microsoft).
Are you behind a proxy? The callback handler sends a request to the provider from the application and not from a browser. For me this froze the whole application. You can set the proxy with OAuth2ClientOptions given to the OAuth2Auth.create
As mentioned in the official vert.x-web document, the handling of the auth flow (including access token request to microsoft) is handled by OAuth2AuthHandler:
The OAuth2AuthHandler will setup a proper callback OAuth2 handler so the user does not need to deal with validation of the authority server response.
This being said, there is no need for application to manually handle it. Instead of using example from vertx-auth, try this one instead which actually uses OAuth2AuthHandler.

User authentication and user related content using java jax-rs and angular js

I am trying to get a grasp on how to create a web application using REST (jersey) on the server side, and angularJS on the client, where a user can register/sign in in a secured fashion.
Once a user is signed in, I want to show user related content (his profile).
There are a few questions on this topic but are focused on specific aspects rather then a complete example, so there are few things I'm still missing.
to be more specific:
How do I use HttpServletRequest.login? the documentation specifies "Validate the provided username and password in the password validation realm used by the web container login mechanism configured for the ServletContext"
How do I specify a login mechanism?
Once a user is signed in, how can i display his profile?
Also, an example of such web application would be wonderful.
I think it will be helpful for you to take a look at Stormpath. In your backend, you can use the Stormpath Java SDK to easily delegate all your user-management needs. Since you are specifically interested in the login functionality, this is the way you would do it with Stormpath:
There are three options here...
You can completely delegate the login/register functionality to Stormpath via its IDSite
You can also delegate it to our Servlet Plugin
You want to develop your own login
If you decide to go with option 3:
Your front end will display the login form (BWT, Stormpath also supports Google, Facebook, LinkedIn and Github login)
When the user presses the login button, your front end will send the credentials securely to your backend-end thorough its REST API.
Your backend will then try to authenticate the user against the Stormpath Backend:
/** This code will throw an Exception if the authentication fails */
public void postOAuthToken(HttpServletRequest request, HttpServletResponse response) {
Application application = client.getResource(applicationRestUrl, Application.class);
//Getting the authentication result
AccessTokenResult result = (AccessTokenResult) application.authenticateApiRequest(request);
//Here you can get all the user data stored in Stormpath
Account account = accessTokenResult.getAccount();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
//Here you can also return some of the user data to your front-end in the response
JSONObject dataSet = new JSONObject();
dataSet.put("Email", account.getEmail());
dataSet.put("Username", account.getUsername());
response.getWriter().print(dataSet.toString());
response.getWriter().flush();
}
Please take a look here for more information
Hope that helps!

Authenticate credentials with LDAP for specific requests

I have a web application that I deploy using JBoss 5.2. In order for a user to use the application, he/she must authenticate with an LDAP server (using simple authentication) with a username and password. This is all done through setting up the login-config.xml for JBoss and providing a <login-module> with our implementation.
The problem comes in here: After having logged in, I have a scenario that requires the user to provide a username & password when a particular action is performed (which I will also authenticate with the LDAP server). I want to be able to reuse the same mechanism that I use for authenticating the user into the web application.
My form to log in to the application posts to j_security_check so in accordance with this, I was trying to send a request to j_security_check but JBOSS returns a 404. From reading around a bit, I've gathered j_security_check cannot be accessed by any arbitrary request and must be in response to a challenged request to a secured resource.
So then, how can I authenticate the second set of credentials the user has provided with the same LDAP server?
EDIT:
To clarify, the question is how to send the user's credential inputs to the LDAP server for authentication. Grabbing the input from the user, etc. is all done. All that is left is to take this input and send it to the LDAP server and get the response (which is where I am stuck).
If it helps to mention, the login to the web application uses a custom class that extends UsernamePasswordLoginModule.
So, after lots of research, I ended up finding a solution for JBoss environments (which is what I'm using).
Once you capture the user's credentials, you send them to your server via a POST/GET and your server can perform the following to use whatever authentication policy you have configured (in login-config.xml) to verify the credentials:
WebAuthentication webAuthentication = new WebAuthentication();
boolean success = webAuthentication.login(username, password);
To expand on this, I was also able to check the user's role/group via the HttpServletRequest (which is passed into my server-side handler):
boolean userIsInRole = servletRequest.isUserInRole("nameOfGroup")
The spring security documentation explains it
Wanted to add another answer for JBoss 6.2+, where WebAuthentication no longer exists.
I've used the creation of a LoginContext to achieve the same result:
String SECURITY_DOMAIN_NAME = "ssd"; // the security domain's name from standalone.xml
String username = "user";
String password = "password";
LoginContext lc = null;
try {
lc = new LoginContext(SECURITY_DOMAIN_NAME, new UsernamePasswordHandler(username, password.toCharArray()));
lc.login();
// successful login
} catch (LoginException loginException) {
// failed login
}
And the use uf lc.getSubject().getPrincipals() to verify roles.

Google Client Login Handling AuthToken

I have a non-gae, gwt application and it have a module that allows users to create documents online via google docs api.
To do that, i first ask user to enter the name and type of the document, than create a new document via google docs api with the given parameters and onSucces part of that servlet returns edit link which is used in client side to open a new page to edit the created document.
Problem that, eachtime i try to open that editLink user have to enter login informations. To solve this i try to use Google Client Login but i am totally lost i think.
First i have username and password of user and can directly use them, after searching i tried some examples which usually returns a token like this and that. Now what should i do with token? How can it be used to complete login process or should totally find another way to do login? All those oauth1,oauth2 and etc. documentations confused me a little bit.
here are my steps;
Server side;
LinkedHashMap<String, String> hashMap = new LinkedHashMap<String, String>();
// Login
DocumentList docList = new DocumentList("document");
docList.login(ServletUtil.googleDocsLoginInfo().get("username"), ServletUtil.googleDocsLoginInfo().get("password"));
//Create document with a unique suffix
String docName= parameterName+ "-Created-" + new Date();
docList.createNew(docName, dosyaTur);
// Find the created document and store editLink
DocumentListFeed feed = docList.getDocsListFeed("all");
for (final DocumentListEntry entry : feed.getEntries()) {
if (entry.getTitle().getPlainText().equals(docName)) {
hashMap.put("editlink", entry.getDocumentLink().getHref());
}
}
return hashMap;
And Client side;
#Override
public void onSuccess(LinkedHashMap<String, String> result) {
String editLink = result.get("editlink");
Window.open(editLink,"newwindow","locationno");
}
Thanks for your helps.
If I may suggest using OAuth instead of Client Login, which is outdated and less secure.
The functionality is basically the same (for OAuth 2.0 there are more ways to handle the login).
I know, trying to understand how to access the api via OAuth is very confusing, so I try to break it down a little:
If you use OAuth 2.0 you may want to use a library like this one or you can try out my own (although I wrote it for Android, this could work with other Java Apps including Web Apps)
This is what happens when a user logs in the first time with your app:
> Your App sends an authorization request containing some information about your app - for example your app needs to be registered with google and therefore has a special application key
< The Server sends you a url, open it in a new browser window and let the user login. There he will be asked to allow your app to access his account (or some parts of it) - when he confirms he will be prompted an Authorization Code which he needs to copy
> The user gets back to your app, where you will ask him for the authorization code. After he gave it, your app connects again with the server and sends the code as some kind of authorization grant of the user.
< The Server answers with a access token
All you need to do is use this access token (also called a bearer token) in all your requests to the server hidden in the header message.
I am sorry I can't give you a more precise answer right now, since I never used GWT. All I can say is, try using OAuth2, it is actually very simple (after you learn what all this confusing things like authorization flow, bearer token etc are) and really comfortable for your user, once the he has done the first login.

Invalid parameter exception on client.auth_getSession() in Facebook java API

I want to connect to a my facebook application using the facebook java api 2.1.1(http://code.google.com/p/facebook-java-api/). My application is in "Desktop" mode so I should be able to access it outside of a web application. I have not defined any callback url for it as well. My code looks something like this.
FacebookJsonRestClient client = new FacebookJsonRestClient( FB_APP_API_KEY, FB_APP_SECRET );
String token = client.auth_createToken();
HttpClient http = new HttpClient();
http.setParams(new HttpClientParams());
http.setState(new HttpState());
final String LOGIN = "https://login.facebook.com/login.php";
GetMethod get = new GetMethod(LOGIN + "?api_key=" + FB_APP_API_KEY + "&v=1.0&auth_token=" + token );
http.executeMethod(get);
PostMethod post = new PostMethod(LOGIN);
post.addParameter(new NameValuePair("api_key", FB_APP_API_KEY));
post.addParameter(new NameValuePair("v", "1.0"));
post.addParameter(new NameValuePair("auth_token", token));
post.addParameter(new NameValuePair("email", "my-email"));
post.addParameter(new NameValuePair("pass", "my-password"));
http.executeMethod(post);
String session = client.auth_getSession(token);
However instead of returning the session the API throws an exception:
com.google.code.facebookapi.FacebookException: Invalid parameter
at com.google.code.facebookapi.FacebookJsonRestClient.parseCallResult(FacebookJsonRestClient.java:354)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:535)
at com.google.code.facebookapi.ExtensibleClient.callMethod(ExtensibleClient.java:472)
at com.google.code.facebookapi.FacebookJsonRestClient.auth_getSession(FacebookJsonRestClient.java:278)
Can anyone please tell me whats wrong with this code? And what is the correct way to access a facebook application in desktop mode using the java api (v. 2.1.1).
Thanks for your help.
Regards
Nabeel Mukhtar
As far as I understand FB's API, you're not supposed to provide username and password manually but instead let the user input them manually and then allow the Facebook Login to redirect the user back to your application. This means that instead of providing "email" and "pass" you provide "next" and "cancel" URL:s instead.
This is purely a security feature of FB API and while the theory behind it is alright, the execution is far from optimal.
See this discussion thread on the Google Code site. There's a link in the that thread to a wiki page which explains how to do desktop auth.

Categories