Spotify logout on android - java

i have this code to log in to spotify in my app. I using the offical spotify lib.
public void spotifyLoginBtnClicked(View v){
//start the authentication for spotify
AuthenticationRequest.Builder builder = new AuthenticationRequest.Builder(clientID, AuthenticationResponse.Type.TOKEN, redirectURI);
builder.setScopes(new String[]{"user-read-private", "streaming"});
AuthenticationRequest request = builder.build();
// open LoginActivity
AuthenticationClient.openLoginActivity(this, activityIdentification, request);
}
Im wondering now how i can create a logout button. Because once logged in, if i press the login button again, it just returns. So i'am unable to change the user. I havent found anything in the java doc.

I just found this document which looks similar to the code you pasted for logging in.
In there it mentions a few methods for logging the user out but I think the main block of code you will need is:
To log out and clear all stored tokens, use the AuthenticationClient#clearCookies method. Both Spotify and Facebook tokens will be removed.
I would go and check that article I linked above as there is edge cases that might be important for your project.
Happy Coding!

Related

Wicket: double login required due to extended browser info

I have a Wicket 8.6 application. Currently, when logging in to the application, mostly (does not always happen) the user has to login twice. After the first login (after entering the credentials and clicking the submit button) a white page appears saying "If you see this, it means that both javascript and meta-refresh are not support by your browser configuration. Please click this link to continue to the original destination." This is the BrowserInfoPage. After a few seconds the user is redirected to the login page again where he/she has to enter his/her credentials again and press the login button. This time, the user logs in successfully. My question is, how do I prevent that the user hast to enter his/her credentials twice.
From my research I know that it has something to do with the collection of extended browser info. In the init method of my WicketApplication class, I had the following code:
getRequestCycleSettings().setGatherExtendedBrowserInfo(true);
However, I already commented out this code several month ago. For some reason, the described effect occurs for every new deploy now. Maybe a newly added package in the application is the reason for it. I don't know. Is there a possibility to prevent this second login maybe by creating a customized bowser info page which forwards the login? Please point me in the right direction. Thanks.
After some research, I came up with a work around. It is probably not very efficient but it works for me so far. In my custom Session class which inherits from AuthenticatedWebSession, I added the following code.
#Override
protected WebPage newBrowserInfoPage() {
final Request request = RequestCycle.get().getRequest();
if(request.getUrl().toString().contains("LoginPage")) {
if(!isSignedIn()) {
signIn(username, password);
}
PageParametersEncoder encoder = new PageParametersEncoder();
PageParameters parameters = encoder.decodePageParameters(request.getUrl());
String url = parameters != null && parameters.get("originUrl") !=null && !parameters.get("originUrl").isNull() && !parameters.get("originUrl").isEmpty()?
parameters.get("originUrl").toString("pages/home"):"pages/home";
String finalUrl=url.startsWith("pages/")?url.substring("pages/".length()):url;
throw new RedirectToUrlException(finalUrl);
}
return super.newBrowserInfoPage();
}
Some explanation to the code. As mentioned in the question, I want to prevent the user from logging in multiple times. Thus, I check if the request comes from the LoginPage and perform my work around only in that case.
During my implementation, I realized, that the method newBrowserInfoPage is called in the process when I call session.signIn(username,password); on my LoginPage. In this signIn process the authenticate method of my custom Session is called but the signedIn flag in the AuthenticatedWebSession is not changed (keeps false on successfull authentication). Is this a bug? Thus, I have to login again to set the flag to true.
Finally, I read the URL of the LoginPage where I have stored the target URL and forward the user to the target URL.
I am aware this is probably not the best approach but it is the only solution I came up with. If someone has a better idea, I am happy to hear it.

Google home doesn't ask sign in questions. But it works on console.actions testing platform

I'm trying to develop google login intent to identify users. I'm using the default code on developer site https://developers.google.com/actions/identity/google-sign-in
For some reason it works on actions simulator, but not on my home assistant. Shouldn't it work exactly the same on my Google assistant device?
As far as i understand Log in should be triggered by new SignIn() and google handles the confirmation questions. And thats exactly as it works in simulator.
//triggered by user
#ForIntent("Start Signin")
public ActionResponse text(ActionRequest request)
{
ResponseBuilder rb = getResponseBuilder(request);
return rb.add(new SignIn().setContext("To get your account details")).build();
}
//triggered by login event in dialogflow
#ForIntent("Get Signin")
public ActionResponse getSignInStatus(ActionRequest request)
{
if (request.isSignInGranted())
{
...
}
}
On Google assistant device the conversation just stops after asking for login intent. And in simulator i do get the correct google generated sign in questions.
Seems like google did something and now everything is working again. I didn't do any changes.

Java Read Facebook Wall

I'm building a web portal by using Java; besides other requirements, I'm struggling my mind one one very simple (at least at first view) requirement:
my customer wants on his portal the first N posts of his facebook wall
and he wants to read the first N tweets of his twitter page
Since my java code is based on Spring, I wanted to use spring social, spring social twitter and spring social facebook in order to satisfy the requirement
With twitter I had no problem; in fact I
created an app on twitter
got twitter app id and app secret
prepared code
In a couple of hours, all worked pretty good
Problems were born with facebook and it's a lot of time I'm fighting with it
I passed from spring social to facebook4j (since this last one seems to me stronger).
I did the following
created an app on FB
got the facebook appId and appSecret
told to the code that I need the read_stream permission
prepared the code
But I'm not able in reading posts from my wall
Is there anyone who was able in satisfying this kind of scenario?
here my facebook4j code
private static final Logger log = LoggerFactory.getLogger(FacebookTest.class.getName());
public static void main (String[] a)
{
try
{
ConfigurationBuilder cfgBui = new ConfigurationBuilder();
cfgBui.setDebugEnabled(true);
cfgBui.setOAuthAppId(myAppId);
cfgBui.setOAuthAppSecret(myAppSecret);
cfgBui.setUseSSL(true);
Configuration cfg = cfgBui.build();
FacebookFactory ff = new FacebookFactory(cfg);
OAuthSupport support = new OAuthAuthorization(cfg);
support.setOAuthPermissions("read_stream");
AccessToken appAccessToken = support.getOAuthAppAccessToken();
Facebook face = ff.getInstance(appAccessToken );
ResponseList<Post> posts = face.searchPosts("test");
for (Post post : posts)
{
System.out.println(post.getId());
}
} catch (Exception e)
{
log.error("Errore", e);
}
}
As far as I understood, I should need the user access token, but I don't know how to generate it; should I create a login flow and show to the user the FB login dialog? If so, why should I create app id and app secret? They have no sense in my scenario
Moreover...in my case...the server side should authenticate on FB and read posts from a well know user wall (the wall of my customer...) so....where should I present the login dialog? where should I redirect after the FB login?
Is there any good man :) who can clarify to me the FB read post flow?
You MUST use one of the possibilities to authorize the user (with read_stream) in order to get access to his stream. Here´s the link to all the possibilities: https://developers.facebook.com/docs/facebook-login/v2.2
You can also generate Access Tokens with the Graph API Explorer: https://developers.facebook.com/tools/explorer/
Detailed information about Access Tokens and how to generate them can be found in the following links:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
Keep in mind that an Extended User Token only lasts for 60 days, after that your customer would have to refresh it manually. In general, you are not allowed to use User Profiles for commercial reasons, and it´s very unusual to show a User stream on a website.
Better: Use a Facebook Page. /page-id/feed with an Extended Page Token that lasts forever.
If you use spring-social-facebook, you could let the user login via (front-end login flow) and then you can access the users wall. However, user would need to login and authorize your app to perform the operations.
Here is a spring social sample project that demo's how spring-social-facebook login is done https://github.com/spring-projects/spring-social-samples
Also, within your java code you can use feedoperations to gather information about home feed and also query against it. Checkout the documentation.
facebook.feedOperations().

How to handle urn:ietf:wg:oauth:2.0:oob redirect in Google Calendar API Authorization

I am currently working on a installed desktop application implemented in java. I intend to integrate Google Calendar API into the application.
During the authorization procedure, I come to this stage where I am able to get the authorization code only through triggering a browser where the user consent page is displayed. Users then have to click "accept" and will be redirected to a webpage where the authorization code is presented. Users are to copy this code to the Eclipse System.in in order for the authorization process to continue (to exchange the authorization code for a TokenResponse).
My question is that how can I simplify this process so that the user won't have to do this stupid copy-and-paste stuff for the authorization code to be received? (This won't work anyway, if the project is compiled into a jar file...) Currently all I know is that I will need to provide a callbackurl or something, I just can't figure this out. Therefore, I would appreciate a more concrete answer, rather than simply tell me the concepts.
Thanks in advance.
You have to use a service account (which comes with a private key) in order to skip the step involving user interaction. There is a detailed guide about this here.
The oauth2 authorization grant flow (I think, that's what you are doing) defines that your application gets the flow back via a HTTP redirect.
It's like this:
Your application opens a socket and listens there for HTTP requests
It now opens the browser and lets the user enter his/her credentials
The user clicks submit and sends the credentials to the oauth server
The server checks the credentials and, if correct, redirects the browser to your application (to the socket you opened in 1.)
Your application gets the auth code from the browser and exchanges it with the access ticket.
To let the server know where to redirect to, you use the oauth parameter redirect_uri in step 2.
This page seems to indicate that the auth code is in the title of the browser window, and the desktop app is expected to read it from there. (Gack.)
I found the solution.
Note: this is java code, but I bet it works the same way in all other languages.
The problem is my server is very restricted with and so I cannot start either browser there(since that is just a server without UI), either start localhost server for getting the code.
All you need is custom VerificationCodeReceiver:
VerificationCodeReceiver inbrowserListener = new VerificationCodeReceiver() {
#Override
public String getRedirectUri() throws IOException {
return "urn:ietf:wg:oauth:2.0:oob";
}
#Override
public String waitForCode() throws IOException {
// Reading console line
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
return reader.readLine();
}
#Override
public void stop() throws IOException {
}
};
then simply use it in usual flow:
private static Credential getCredentials() {
.....
return new AuthorizationCodeInstalledApp(flow, inbrowserListener).authorize("user");
}

TwitterException {statusCode=403, retryAfter=0, rateLimitStatus=null}

I have recently noticed that I keep getting a 403 error while doing twitter search. My application was working until couple of days back when i noticed the error.
I checked with Twitter & they say my IP is not blocked, I am also within the rate limit = about 60 search requests/per hour.
Here's how i was initializing the Twitter object -
private static Twitter TWITTER_CLIENT = new TwitterFactory().getInstance();
After i noticed the error, i tried the following & still no success -
private static Twitter TWITTER_CLIENT = new TwitterFactory().getInstance("user", "password");
Here's how i am searching -
TWITTER_CLIENT.search(new Query("#keyword1 OR #keyword2"));
I tried this URL (curl http://search.twitter.com/search.json?q=ipad) from my server & it works alright.
Following is the exception. I am on java6 + Twitter4j v2.1.2. Would really appreciate any help. Thanks.
TwitterException{statusCode=403, retryAfter=0, rateLimitStatus=null}
at twitter4j.internal.http.HttpClientImpl.request(HttpClientImpl.java:301)
at twitter4j.internal.http.HttpClientWrapper.request(HttpClientWrapper.java:68)
at twitter4j.internal.http.HttpClientWrapper.get(HttpClientWrapper.java:82)
at twitter4j.Twitter.search(Twitter.java:193)
Most likely the reason is basic auth shutdown by Twitter (aka OAuthcalypse):
Basic Auth Shutdown
You need to switch to using OAuth.
Recently i got the same error while executing similar code.
To fix it, please go to
https://apps.twitter.com/app/your_app_id
Click on Keys and access token
In Access Level, click modify app permission and choose the 3rd option: Read, Write and Access direct messages
Click on update. ( Note: you might have to add your mobile no and verify with otp to get this access if you dont have your no added in twitter)
Regenerate both Consumer key & secretand Access token & secret using the clickable button
Us e the new keys in your program
And you are done! Your program will start working.

Categories