Force.com OAuth 2.0 Scribe Java Example

OAuthServiceConfig and OAuthServiceProvider Bean in ApplicationContext

<bean id="salesforceServiceConfig" class="com.example.oauth.OAuthServiceConfig">
		<constructor-arg value="xxx" />
		<constructor-arg value="xxxx"/>
		<constructor-arg value="https://www.example.com/oauth/salesforce"/>
		<constructor-arg value="com.example.oauth.SalesforceOauthApi"/>
	</bean>
	<bean id="salesforceServiceProvider" class="com.example.oauth.OAuthServiceProvider">
		<constructor-arg name="config" ref="salesforceServiceConfig" />
	</bean>

SalesforceOauthApi extends DefaultApi20

package com.example.oauth;

import org.scribe.builder.api.DefaultApi20;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.OAuthConfig;
import org.scribe.model.Verb;

public class SalesforceOauthApi extends DefaultApi20{

	private static final String ACCESSTOKEN = "https://login.salesforce.com/services/oauth2/token?grant_type=authorization_code";
	
	@Override
	public String getAccessTokenEndpoint() {
		return ACCESSTOKEN;
	}

	@Override
	public String getAuthorizationUrl(OAuthConfig config) {
		return String.format("https://login.salesforce.com/services/oauth2/authorize?client_id=%s&response_type=code&redirect_uri=%s&display=popup&scope=%s", config.getApiKey(), config.getCallback(), "full refresh_token");
	}
	
	 @Override
	 public Verb getAccessTokenVerb(){
	       return Verb.POST;
	 }
	
	@Override
	 public AccessTokenExtractor getAccessTokenExtractor() {
	    return new JsonTokenExtractor();
	 }
}

Spring MVC SalesforceController for requesting access token

package com.example.oauth.controller;

import static org.springframework.web.context.request.RequestAttributes.SCOPE_SESSION;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import com.example.oauth.OAuthServiceProvider;

@Controller
@RequestMapping("/oauth/salesforce")
public class SalesforceController {

	@Autowired
	@Qualifier("salesforceServiceProvider")
	private OAuthServiceProvider salesforceServiceProvider;
	
	private static final Token EMPTY_TOKEN = null;

	@RequestMapping(value = "/login-salesforce", method = RequestMethod.GET)
	public String loginToSalesforce(Map<String, Object> map, WebRequest request) {
		OAuthService service = salesforceServiceProvider.getService();

		String authUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
		System.out.println("RequestToken: " + authUrl);
		return "redirect:" + authUrl;
	}

	@RequestMapping(value = { "" }, method = RequestMethod.GET)
	public String callback(
			@RequestParam(value = "oauth_token", required = false) String oauthToken,
			@RequestParam(value = "code", required = false) String oauthVerifier,
			WebRequest request, Map<String, Object> map) {

		OAuthService service = salesforceServiceProvider.getService();

		// getting access token
		Verifier verifier = new Verifier(oauthVerifier);
		Token accessToken = service.getAccessToken(EMPTY_TOKEN, verifier);

		// store access token as a session attribute
		request.setAttribute("oauthAccessToken", accessToken, SCOPE_SESSION);

		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes();
		HttpSession session = attr.getRequest().getSession(false); // create a
																	// new
																	// session
		session.setAttribute("accessToken", accessToken);

		return "settings";
	}
}

44 Comments

  1. Oh my goodness! a tremendous article dude. Thanks Nonetheless I am
    experiencing subject with ur rss . Donཿt know why
    Unable to subscribe to it. Is there anybody getting an identical rss drawback?
    Anyone who is aware of kindly respond. Thnkx

  2. In plants vs. zombies 2 cheats fact, with technology developing at a fast pace.
    Even the submission process is no more treated only as
    a guide for help.

  3. Well if you want to spend their free time by playing it.
    To new editors, and sizzling movie character game that is unsuitable
    stardom hollywood cheats for you to choose android.

    This list may help you get bored with it. Immersive 3D graphics will appear amazing on your HD
    TV screen. If you are interested in gaming can be done on different sites and the majority
    of the fun through them.

  4. I have noticed that online education is getting common because obtaining your college degree online
    has developed into a popular option for many people. A huge number of people
    have definitely not had an opportunity to attend
    a conventional college or university yet seek the raised earning possibilities and career advancement that a Bachelor’s Degree provides.
    Still other individuals might have a qualification in one field but want to pursue something they
    now have an interest in.

  5. Paige says:

    I also have a several helpful hints to keep your expenses cost approach down.
    Most children who exhibit violent or aggressive behaviors suffer from low self esteem
    and self image. Parents who are concerned about their children’s ability to get
    into college are interested in seeing what options Toronto private schools have to offer.

  6. The Entente: World War I Battlefields Total Annihilation. He also learns that here is a good
    side to the Force, and a bad side. No more binging
    on ice cream as a mid morning or mid afternoon snack.

  7. I like the helpful info you prrovide in your articles.
    I will bookmark your weblog and check again here frequently.
    I’m quite sure I will learn lots of new stuff right here!

    Good luck for the next!

  8. Hello! Do you know if they make any plugins to
    safeguard against hackers? I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

  9. Anderson says:

    Hello, after reading this amazing post i am also glad to share my experience
    here woth mates.

  10. The best way to get in touch with your personal shortcomings is to get involved
    in a relationship. That day a whole village will be looted, pillaged and destroyed because we couldn’t
    hold back the terrible, vicious beast. are few swords that are designed to relive the glorious history of
    medieval period.

  11. The benefit to do it this way is that we won’t risk getting off beat.
    The first thing is finding a reliable source that can provide you with the entire book.
    In their book Microcosmos, biologist Lynn Margulis and Dorion Sagan explain sex as the “union of genetic material from more than one source to produce a new individual.

  12. ncipe Real and comfortable holiday apartments in the old town Alfama or Castelo.
    Strong Style instead is wrestling that attemtped to ground itself
    in reality. In their book Microcosmos, biologist Lynn Margulis and Dorion Sagan explain sex as the
    “union of genetic material from more than one source to produce a new individual.

  13. olympia says:

    Hi this is kind of of off topic but I was wanting to know if blogs use WYSIWYG editors or
    if you have to manually code with HTML. I’m starting a
    blog soon but have nno coding expertise so I waanted to get guidance
    from someone with experience. Any help would be enormously appreciated!

  14. This website was… how do I say it? Relevant!! Finally I’ve found something
    which hedlped me. Many thanks!

  15. It’s a pity you don’t have a donate button! I’d mmost certainly donate to this superb blog!
    I suppose for now i’ll ettle for bookmarking and
    adding your RSS feed to my Google account. I look forward to brand new updates annd
    will share this website with my Facebook group. Chat soon!

  16. Numbers says:

    I love what you guys are up too. This type of clever work
    and exposure! Keep up the terrific works guys I’ve included you guys tto my personal blogroll.

  17. Hi friends, good article and fastidious arguments commented here, I am realy enjoying by these.

  18. Thanks for the marvelous posting! I truly enjoyed reading it, you can be a great author.I will always bookmark
    your blog and will eventually come back at some point. I want to encourage one to continue your grezt job,
    have a nice holiday weekend!

  19. Terese says:

    But they usually beat around the bushes and expect you to do
    what Arnold does, a million sets and 5 hours of steady pumping
    iron. Think about the demographic of the user, the
    size of the space and of course the budget. ” As a result of the fact that physical education programs are being cut, the U.

  20. Larhonda says:

    Wow, this piece of writing is good, my sister is analyzing these kinds off things,
    therefore I am going to inform her.

  21. This is a topic that’s close to my heart… Best wishes! Exactly where arre your contact details though?

  22. Hey! I coul have sworn I’ve been to this site before but after browsing through some of
    the post I realized it’s new to me. Anyhow, I’m definitely happy I found it and I’ll be bookmarking and checking back
    often!

  23. Τhanks fօr sharing ʏߋur thoսghts on 3 week diet plan schedule.

    Ʀegards

  24. Hi there to all, how is the whole thing, I think every one is getting more from
    this web page, and your views are pleasant in favor of new users.

  25. Magnificent web site. Lots of helpful information here. I am sending
    it to some pals ans additionally sharing in delicious.
    And certainly, thank you for your sweat!

  26. lg says:

    Everything is very open with a precise clarification of the issues.
    It was ttuly informative. Your site is useful. Thanks for sharing!

  27. Hack Eternity Warriors 3 says:

    Android market is updated regularly with new apps
    that are along with many features in order to
    capture the attention of the mobile users. I will provide more information in my next article about how the devices are impacting i
    – Phone Game Development and Android Game Development.

    These are some instances of possibilities but you can get a lot from
    a reputed i – Phone apps developer company or an experienced i – Phone developer.

  28. paket wisata says:

    This website was… how do I say it? Relevant!! Finally I’ve found something which helped me.
    Thank you!

  29. You should take part in a contest for one of the highest quality blogs online.
    I most certainly will recommend this site!

  30. Velva says:

    Great beat ! I would like to apprentice even as you amend your site, how could i subscribe for a weblog
    site? The account helped me a appropriate deal. I had been a little bit familiar
    of this your broadcast offered brilliant transparent concept

  31. lisinopril says:

    I like the helpful info you provide in your
    articles. I’ll bookmark your weblog and check again here regularly.
    I’m quite sure I’ll learn many new stuff right here! Best of luck for the next!

  32. The unique owner of the pattern even included the journal clipping in the sample envelope.

  33. Simply want to say your article is as astounding.
    The clarity to your submit is just spectacular
    and i can assume you’re an expert in this subject.

    Well with your permission allow me to take hold of your feed to
    stay updated with drawing close post. Thank you
    one million and please keep up the gratifying work.

  34. It’s perfect time to make a few plans for the longer term and it’s time to be happy. I have read this publish and if I may I desire to suggest you few fascinating things or advice. Perhaps you can write subsequent articles regarding this article. I desire to learn more issues about it!|

  35. essay says:

    It’s very trouble-free to find out any topic on web as compared
    to textbooks, as I found this post at this site.

  36. You need to be a part of a contest for one of the greatest blogs
    on the web. I most certainly will highly recommend this website!

  37. stickers says:

    For latest news you have to pay a quick visit web and on web I found this web
    page as a best web site for newest updates.

  38. whoah this weblog is magnificent i love reading your posts.
    Stay up thhe great work! You understand, many people
    are searching around for this info, you could help them greatly.

  39. palabra4 says:

    Yes! Finally something about america.

  40. If some one desires to be updated with latest technologies
    after that he must be visit this website and be up to date everyday.

  41. I believe you have mentioned soje very interesting points , appreciate it for the post.

  42. However, teaser trailers and featured trailers
    are usually released on thhe Internet and it is estimated that every year over ten billion video trailers are watched online.
    Nick just appens tto be a cousin of Daisy, who lives with Tom across the water
    from Gatsby. The next version of Windoows beyond Vista iis Windows 7.

  43. Alethea says:

    Wow, that’s what I was exploring for, what a information!
    existing here at this weblog, thanks admin of this web site.

  44. หนัง x
    Hey there, I think your blog might be having browser compatibility
    issues. When I look at your blog site in Opera, it looks
    fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, amazing blog!

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s