How to store cookies, and reuse them in another session - java

I am trying to authenticate a user from a web page,
store the cookies and load an rss-feed from a different web page as the authenticated user.
Im using a webView with this WebViewClient which loads an RSS-link when the user has authenticated himself (url is finished loading): - This does not redirect until after user logs in and presses another link.. How can I redirect straight after login?
class LinkWebViewClient extends WebViewClient
{
//Callback method for when the url is finished loading
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
view.loadUrl("https://something.com/todays-rssfeeds");
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
};
}
Main Problem is when i try to load the second page, i have to re-authenticate myself because it is not the same session..
Any suggestions to how i can solve these problems?
These are my Cookie settings:
/
/ use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
//After Login
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
if (!cookies.isEmpty()) {
for (int i = 0; i < cookies.size(); i++) {
cookie = cookies.get(i);
}
}
Cookie sessionCookie = cookie;
if(sessionCookie != null)
{
String cookieString = sessionCookie.getName() +"="+sessionCookie.getValue()+"; domain="+sessionCookie.getDomain();
cookieManager.setCookie(myUrl, cookieString);
CookieSyncManager.getInstance().sync();
}
All help appreciated! Thanks

Cookies are tied to domain, but if these pages share authentication system (unlikely, I think), you could manually pass session identifier to the second page. If not, the question is how that second page should authorize user?

Related

How to authenticate logged in user when refreshing single page application using AngularJS without "Routing"?

I searched a lot of resources but none was appropriate to my problem.I am working on single page application (SPA) project ,and I want a logged in user to stay logged in whenever he refreshes the page but without routing.
I have tried to call session authentication servlet in the main controller of the page(this servlet checks whether the session exists or not),but it did not work.
Note: The session is created once the user log in or sing up.
Here is SessionAuthServlet.java:
HttpSession session = request.getSession(true);
User u=(User) session.getAttribute("usersession");
try{
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();
if(u != null)
{
out.println("{\"+success+\"}");
out.close();
}
else
{
out.println("{ \"result\": \"fail\"}");
out.close();
}
}catch (IOException e) {
e.printStackTrace();
}
MainController in HTML single page application:
appvar.controller('MianController',['$scope','$http','$rootScope',function($scope, $http,$rootScope) {
$rootScope.sessionvalid=function(){
$http.get("http://localhost:8080/MyProject/SessionAuthServlet")
.success(function(response) {
if (response.result=="fail")
{
//***Show the view for not logged user
}
//***Show the view for logged user
}
$rootScope.sessionvalid();
});
}
}]);
Any ideas how to deal with this?
Please guide me
Thanks
Here is how you can stay logged after page refresh without using routing.
You will need below three things
A angular service to hold user information and if he is authenticated or not.
A window sessionstorage to save user information. Even if the page is refereshed the user information will persist in sessionstorage
An interceptor to set request and response.
Service code -
app.service('AuthenticationService', function() {
var auth = {
isLogged: false,
email:"",
isAdmin:false
}
return auth;
});
In your MainController, once user is logged in set the Service AuthenticationService.isLogged = true and $window.sessionStorage = userInfo
Interceptor code-
app.service('TokenInterceptor', function ($q, $window, $location, AuthenticationService) {
return {
request: function (config) {
config.headers = config.headers || {};
if ($window.sessionStorage.token) {
config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
}
return config;
},
/* Set Authentication.isAuthenticated to true if 200 received */
response: function (response) {
if (response != null && response.status == 200 && $window.sessionStorage.token && !AuthenticationService.isAuthenticated) {
AuthenticationService.isAuthenticated = true;
}
return response || $q.when(response);
}
};
});
and in your app.config block add this -
app.config(function($httpProvider){
$httpProvider.interceptors.push(TokenInterceptor);
})
Now your AuthenticationService.isLogged will remain true even if the page is refershed and you can get the logged in user info in the service.

No authorizations to perform actions - but the app is authorized

I would like to use restfb to post to one of my pages. I want to post as the page itself, not as an user posting to the page's wall.
This is the code I'm using:
public class App {
//user token for accessing the page as admin
private static final String INITIAL_ACCESS_TOKEN = "#";
public static void main(String[] args) throws Exception {
restfb();
}
public static void restfb() throws Exception {
DefaultFacebookClient fbClient;
Connection myAccounts;
fbClient = new DefaultFacebookClient(INITIAL_ACCESS_TOKEN, Version.VERSION_2_5);
myAccounts = fbClient.fetchConnection("me/accounts", Account.class);
String pageToken = null;
//retrieve the page token
for(Object a : myAccounts.getData()) {
Account account = (Account)a;
if("MyPage".equals(account.getName())) {
pageToken = account.getAccessToken();
break;
}
}
System.out.println(pageToken); //not null here
//post to the page
fbClient = new DefaultFacebookClient(pageToken, Version.VERSION_2_5);
//"me" should refer to the page itself..?
fbClient.publish("me/feed", FacebookType.class, Parameter.with("message", "Aloha! ;)"));
}
}
I get error
Received Facebook error response of type OAuthException: (#200) The user hasn't authorized the application to perform this action (code 200, subcode null)
I already visited this url:
https://www.facebook.com/dialog/oauth?client_id=###&redirect_uri=###&scope=manage_pages,publish_actions,user_actions:pagealias&response_type=code
It asked me to give permissions to my app to post and manage my pages, and I granted them.
The application is not public, as it is a test application I want to use for development (so I didn't ask for the Review).
What am I missing? Which other permission does the app need in order to work and properly post?
You should request the publish_pages permission to post as page.
https://developers.facebook.com/docs/facebook-login/permissions#reference-publish_pages

Wicket Session with more than one user logged in

I am building my first Java Application with Wicket and have a bit of a problem with Wicket Sessions.
My Problem: When a second User logs into the application he overrides the session for the first user -> both are working on the second session now. Although both Users create a new Session when logging in.
My Code:
WicketSession.java:
public class WicketSession extends WebSession {
private UserBean currentUser;
public WicketSession(Request request) {
super(request);
}
public static WicketSession get() {
return (WicketSession) Session.get();
}
// getter/setter
in my Application class:
#Override
public Session newSession(Request request, Response response) {
return new WicketSession(request);
}
and the login (short version w/o ifs, to make it readable):
#Override
public final void onSubmit() {
if (signIn(wiaUsername, wiaPassword)) {
getSession().bind();
setResponsePage(new CharListDetail());
} else {
error("Unknown username/ password");
}
}
private boolean signIn(String username, String password) {
currentUser = UserProxy.getInstance().getElementByUser(username, password);
WicketSession.get().setCurrentUser(currentUser);
return true;
}
This all works fine for one user. But the moment a second user logs in
WicketSession.get().setCurrentUser(currentUser);
sets the current User to the new User and both logged in Users are the same. How do I prevent this problem?
After lots of searching the net I found the solution.
The problem was that I saved the currentUser as a UserBean and not as a String. I dont know exactly why it doesn't work in Wicket to store the User as a Bean, but now finally it's working.

Android WebView - with authenticated proxy

I am currently trying to debug an Android App built around WebView. The development network environment that I am tasked to deal with (not my choice, it is an 'enterprisey' security decision) is WPA WiFi + proxy server + proxy authentication.
While the instructions on a very helpful previous answer were great, I'm trying to find a way to configure both proxy host:port and username:password.
My constraints are:
Phone is not rooted - trying to reproduce a customer-reported bug, would rather not deviate from typical customer setup
Running a Samsung Galaxy S on Froyo
Built against 2.1
Android apps aren't my usual thing, again not my choice, so if I'm blatantly missing details, be nice ;)
With WebView android proxy configuration, for basic scheme preemptive proxy authentication,
Starting from Android 2.2, the extra header can be set for authentication. The following can add a header for webView's http request:
public void loadUrl(WebView view, String url, String proxyUserName, String proxyPassword){
UsernamePasswordCredentials creds= new UsernamePasswordCredentials(proxyUserName, proxyPassword);
Header credHeader = BasicScheme.authenticate(creds, "UTF-8", true);
Map<String, String> header = new HashMap<String, String>();
header.put(credHeader.getName(), credHeader.getValue());
view.loadUrl(url, header);
}
For older version, the preemptive proxy authentication can be set on mProxyUserName and mProxyPassword in android.webkit.Network by reflection:
public void loadUrl(WebView view, String url, String proxyUserName, String proxyPassword){
try{
Class networkClass = Class.forName("android.webkit.Network");
if (networkClass != null) {
Object networkObj = invokeMethod(networkClass, "getInstance", new Object[]{view.getContext()}, Context.class);
if (networkObj != null) {
Field mProxyUserName = obj.getClass().getDeclaredField("mProxyUserName");
mProxyUserName.setAccessible(true);mProxyUserName.set(networkObj, proxyUserName);
Field mProxyPassword = obj.getClass().getDeclaredField("mProxyPassword");
mProxyPassword.setAccessible(true);mProxyPassword.set(networkObj, proxyPassword);
}
}
}catch(Exception e){
e.printStackTrace();
}
view.loadUrl(url);
}
When you load a new url, both loadUrl() must need to call again. That is very important.
Therefore, a custom WebViewClient should be used to override shouldOverrideUrlLoading(WebView view, String url)
class ProxyAuthWebViewClient extends WebViewClient {
String proxyUserName;
String proxyPassword;
public ProxyAuthWebViewClient(String proxyUserName, String proxyPassword){
this.proxyUserName = proxyUserName;
this.proxyPassword = proxyPassword;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
loadUrl(view, url, proxyUserName, proxyPassword);
return true ;
}
}
And set the WebViewClient on your webView:
webView.setWebViewClient(new ProxyAuthWebViewClient("user", "password"));

Navigate to external URL from a backing bean?

I'm trying to implement proper logout for my Java EE / JSF2 application.
It requires two things:
I need to logout from JAAS and invalidate the session
I then have to navigate to an external URL to fire Siteminder logout
The Siteminder logout URL (configured on the Policy server -> I cannot change it) is outside my applications context. Eg. if my webapp URL is https://localhost:8080/sm/MyWebApp then the logout URL is https://localhost:8080/anotherwebapp/logout.html.
This is the current local logout code:
public void logout() {
System.out.println("Logging out...");
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
try {
request.logout();
} catch (ServletException e) {
e.printStackTrace();
}
HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (session != null) {
session.invalidate();
}
}
And here is the property that produces the logout URL:
public String getLogoutUrl() {
HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
String requestServer = request.getServerName();
String requestScheme = request.getScheme();
int serverPort = request.getServerPort();
String logoutUrl = requestScheme + "://" + requestServer + ":" + Integer.toString(serverPort) + "/anotherwebapp/logout.html";
return logoutUrl;
}
However, I cannot find a JSF2 / Primefaces component that can call logout() then open the external URL. For example, if I have:
<h:outputLink value="#{authBean.logoutUrl}" onclick="#{authBean.logout()}">[Logout]</h:outputLink>
then onclick does not seem to be called.
Another way I tried was putting the external URL to the end of the logout function to have it returned as a navigation string but it is not recognized (also tried with "?faces-redirect=true"...).
Any help would be appreciated.
You can also just use ExternalContext#redirect().
public void logout() throws ServletException, IOException {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
((HttpServletRequest) ec.getRequest()).logout();
ec.invalidateSession();
ec.redirect("http://example.com/anothercontext/logout");
}
No need for an intermediating page with a meta refresh.
You can create a page logout.xhtml, so the code will look like this:
public String getLogoutUrl() {
return "/logout.jsf";
}
and in the page add:
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=https://localhost:8080/anotherwebapp/logout.html">

Categories

Resources