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";
	}
}
Advertisements

44 Comments on “Force.com OAuth 2.0 Scribe Java Example

  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. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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!

  7. 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.

  8. 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.

  9. 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.

  10. 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!

  11. 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!

  12. 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.

  13. 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!

  14. 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.

  15. 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!

  16. 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!

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

  18. 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.

  19. 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

  20. 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!

  21. 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.

  22. 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!|

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

  24. 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.

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

  26. หนัง 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 Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: