share with facebook using Spring-Social and Spring Security - facebook-graph-api

I have integrated social sign-in button [Facebook] with my web application. Its working fine using spring-social and spring security.
In my login.jsp I have:
<!-- Add Facebook sign in button -->
<button class="btn btn-facebook"><i class="icon-facebook"></i>facebook</button>
Now my registrion controller is: This is the place where I am getting a callback from facebook when the user tries to login for the first time from facebook and register the user in my Database.
#RequestMapping(value = "/user/register", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model)
{
LOGGER.debug("Rendering registration page.");
#SuppressWarnings("deprecation")
Connection<?> connection = ProviderSignInUtils.getConnection(request);
RegistrationForm registration = createRegistrationDTO(connection);
LOGGER.debug("Rendering registration form with information: {}", registration);
model.addAttribute(MODEL_NAME_REGISTRATION_DTO, registration);
return VIEW_NAME_REGISTRATION_PAGE;
}
And also the user is getting saved in UserConnection table.
For subsequent login also I am getting the updated connection in my WebRequest
Now I want to create a shareWithFacebook operation for a user who logged in in my application using signwithfacebook button.
For this my controller is:
#RequestMapping(method = RequestMethod.GET)
public String shareWithFacebook(WebRequest request){
Map<String, String[]> params = request.getParameterMap();
String[] head = request.getAttributeNames(WebRequest.SCOPE_REQUEST);
String[] head1 = request.getAttributeNames(WebRequest.SCOPE_SESSION);
return null;
}
Now when I am running this controller in debug mode , then I can see the Connection object is present in my WebRequest object in this controller,
How I can use this connection Object to make any operation, please help

no help from stackoverflow: but actually I got the solution , may it help someone else, thus posting the same:
add this in your social-xml config to initialize FacebookApiHelper
<bean id="facebookApiHelper" class="org.springframework.social.facebook.config.support.FacebookApiHelper">
<constructor-arg index="0" ref="usersConnectionRepository"/>
<constructor-arg index="1" ref="userIdSource"/>
</bean>
Then use the same in ur contoller to work with existing connection object with facebook.
#Controller
#RequestMapping("/facebook")
public class FacebookOperationController {
private static final Logger logger = LoggerFactory.getLogger(FacebookOperationController.class);
#Autowired
protected FacebookApiHelper facebookApiHelper;
#Autowired
UserIdSource userIdSource;
private UsersConnectionRepository usersConnectionRepository;
#Autowired
public FacebookOperationController(UsersConnectionRepository usersConnectionRepository)
{
this.usersConnectionRepository = usersConnectionRepository;
}
#RequestMapping(method = RequestMethod.GET)
public String shareWithFacebook(WebRequest request,Model model){
Facebook facebook = facebookApiHelper.getApi();
Connection<Facebook> connection = usersConnectionRepository.createConnectionRepository(userIdSource.getUserId()).findPrimaryConnection(Facebook.class);
return "tilesname";
}
}
Now we have connection and facebook , enjoy will all api..

Related

No longer working after removing my site from Facebook via "Apps and Websites"

My website (Spring MVC) allows users to sign up by using their Facebook accounts and sign into my site later with their Facebook accounts. I use scribejava (version 6.6.3) (https://github.com/scribejava/scribejava) for the Oauth integration with Facebook.
I have tested a use case and am unable to find a way to resolve it. Here is the list of steps:
The tester goes to my site's "Log in" page, clicks "Log in with Facebook", grants permissions at Facebook, gets redirected to my site, and signs out. This is a normal and successful flow.
The tester sign into Facebook at Facebook.com
The tester goes to Settings->Apps and Websites and removes my site
The tester goes to my site's "Log in" page, clicks "Log in with Facebook" button, gets redirected to Facebook, and sees an error message.
At step 4, the tester always gets an error message at the Facebook site instead of asking the tester to grant permissions again. See the following screenshot:
I cannot find a way at Facebook to remove this message when clicking on the "Log in with Facebook" button. Here is my code for the web interface. Did I miss something?
#RequestMapping( value="/facebook", method = RequestMethod.GET)
public void facebook(HttpServletRequest request,
#RequestParam(value = "page", required = true) String page,
HttpServletResponse response) throws Exception {
try {
OAuth20Service service = new ServiceBuilder(config.getProperty("facebook.clientId"))
.apiSecret(config.getProperty("facebook.clientSecret"))
.callback(getCallback())
.build(FacebookApi.instance());
String authUrl = service.getAuthorizationUrl();
response.sendRedirect(authUrl);
} catch (Exception e) {
response.sendRedirect("/oauthFail");
}
}
#RequestMapping( value="/facebook/callback", method = RequestMethod.GET)
public void facebookCallback(HttpServletRequest servletRequest,
#RequestParam(value = "code", required = false) String code,
#RequestParam(value = "error", required = false) String error,
HttpServletResponse servletResponse
) throws Exception {
try {
OAuth20Service service = new ServiceBuilder(config.getProperty("facebook.clientId"))
.apiSecret(config.getProperty("facebook.clientSecret"))
.callback(getCallback())
.build(FacebookApi.instance());
OAuth2AccessToken accessToken = service.getAccessToken(code);
final OAuthRequest request = new OAuthRequest(Verb.GET, "https://graph.facebook.com/v3.2/me");
service.signRequest(accessToken, request);
final com.github.scribejava.core.model.Response response = service.execute(request);
String body = response.getBody();
JSONObject jObject = new JSONObject(body);
String email = jObject.getString("email");
//success. use the email to create an account or if the email address exists, direct a userto their account page
} catch (Exception e) {
response.sendRedirect("/oauthFail");
}
}
How to handle this situation? I feel either something is wrong is my code or scribejava has a framework issue. Or this is a Facebook specific issue?
I have just tested the case. Couldn't reproduce.
Did you try running this Example
https://github.com/scribejava/scribejava/blob/master/scribejava-apis/src/test/java/com/github/scribejava/apis/examples/FacebookExample.java
?
I think your problem can be with API versions logic in Facebook.
You can try to explicitly use the latest one .build(FacebookApi.customVersion("3.2"))

Unit Test Web API - How to get auth token

I use token auth for my WebApi application.
I have the following ConfigureAuth method in Startup class:
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
and ApplicationOAuthProvider:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await userManager.FindAsync(context.UserName, context.Password);
//ApplicationUser user = new ApplicationUser() { UserName ="a" };
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
so, I should call /Token and pass credentials to get token. It works, but I want to create Unit Test for it. Is it possible?
The only way to do that is by make an integration test, which asserts the full pipeline testing - from request to response. Before the actual test on the server, you can call the token endpoint to get it, and then use it in the actual unit test by attaching it to the response. I have a sample, which uses MyTested.WebApi here:
Sample
You can do the same without the testing library, this is just how to do it.
I like the idea of pluggable configuration.
For Unit Test project, I want to use specific identity and get predictable data fro LDAP. So, i use the following line in my unit test method when setting http configuration:
config.Filters.Add(new WebApiSetIdentityFilter(config, identityName));
where the filter just "hacks" the identity, replacing the fields I need:
public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
//This principal flows throughout the request.
context.Principal = new GenericPrincipal(new GenericIdentity(this.IdentityName, "LdapAuthentication"), new string[0]);
}

How can I integrate OWIN Authentication Middleware and Sitecore

I have implemented an MVC Application running with Sitecore. The Startup class of OWIN have implemented following like that:
[assembly: OwinStartupAttribute(typeof(WebApplication1.Startup))]
namespace WebApplication1.Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<AppIdentityDbContext>(AppIdentityDbContext.Create);
app.CreatePerOwinContext<AppUserManager>(AppUserManager.Create);
app.CreatePerOwinContext<AppRoleManager>(AppRoleManager.Create);
app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
{
Provider = new AppOAuthProvider(),
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/Authenticate")
});
}
}
}
I have expected when I submit a username, password and grant_type value is password with method POST into URL http://<>/Authenticate the token bearer return to allows user can log in. Unfortunately, the Sitecore throw content is not found and I cannot figure out the way let the request going to the OWIN Middle Authorization. How can I sort it out?

How to open URL in new Browser from Silverlight Application

We have MVVM Silverlight application. I am trying to open web url from button click event which happen on client side viewmodel and through invoke method needs to open web url in new browser.
I am using Process.Start method as describe below in Server side code.
var URL = #"http://SiteSelect.aspx";
SecureString secure = new SecureString();
char[] passwordChars = Properties.Settings.Default.Password.ToCharArray();
//converting string to securestring...found from internet
foreach (char c in passwordChars)
{
secure.AppendChar(c);
}
Process.Start(URL,"",Properties.Settings.Default.User,secure,"agent");
this throws an error related to user name and password. I checked user name and password is correct. Anyone have solution or any other method I can able to use?
Thanks,
You create a helper class:
public static class CommonHelper
{
private class HyperlinkButtonWrapper : HyperlinkButton
{
public void OpenURL(string navigateUri)
{
OpenURL(new Uri(navigateUri, UriKind.Absolute));
}
public void OpenURL(Uri navigateUri)
{
base.NavigateUri = navigateUri;
base.TargetName = "_blank";
base.OnClick();
}
}
public static void OpenURL(string navigateUri)
{
new HyperlinkButtonWrapper().OpenURL(navigateUri);
}
}
Usage:
CommonHelper.OpenURL(#"http://SiteSelect.aspx");
You could use this as well :
using System.Windows.Browser;
var uri = new Uri("http://foo.fr");
HtmlPage.Window.Navigate(uri, "_blank");
Easiest way to pass credentials is to put them in the URL, however it's not very secured. Ie:
http://user:password#foo.fr

Ejb jax-rpc web services with basic authentication how to get username and password of a request

The problem is clear as I mentioned in the title, any help would be appreciated...
By the way, my services are running on Jboss 4.2.2GA and I am using MyEclipse7.5
Moreover, here what I have tried before but did not work for me;
#Stateless
#WebService(name = "BaseService", targetNamespace = "http://base.ws.listingapi.gg.com")
#SOAPBinding(style = SOAPBinding.Style.RPC)
#WebContext(contextRoot = "/listingapi/ws")
public abstract class BaseService {
..
MessageContext mctx = webServiceContext.getMessageContext();
webServiceContext.getUserPrincipal(); //WITH THIS ONE I could get the username but of course not password..
System.out.println(mctx.get("password"));
Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
List userList = (List) http_headers.get("Username");
List passList = (List) http_headers.get("Password");
[SOLVED]
I have found the solution, here it is;
#Context
protected HttpServletRequest request;
Or
#Context
protected WebServiceContext context;
...
request.getUserPrincipal().getName();
//OR
context.getUserPrincipal().getName();
//will return the username used to getting logged in
[SOLVED] I have found the solution, here it is;
#Context
protected HttpServletRequest request;
Or
#Context
protected WebServiceContext context;
...
request.getUserPrincipal().getName();
//OR
context.getUserPrincipal().getName();
//will return the username used to getting logged in