I have been digging Spring Social (1.0.2.RELEASE) for Facebook. I couldn't find out how to send apprequest via spring social. I already have an application on facebook with keys and stuff. I can fetch friends etc. but cannot send apprequest to a particular facebook user. Would really appreciate.
The following example should do the trick - i.e. create an app access token and then create the request using a FacebookTemplate which has been initialised using the created app access token
// retrieve app access token
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=<app_id>&client_secret=<app_secret>", String.class);
String appAccessToken = result.replaceAll("access_token=", "");
// create the request
FacebookTemplate appRequestTemplate = new FacebookTemplate(appAccessToken);
String userId = "1234567890";
MultiValueMap<String, Object> requestData = new LinkedMultiValueMap<String, Object>();
requestData.set("message", "Sending a request through to you...");
String resultOfApprequest = appRequestTemplate.publish(userId, "apprequests", requestData);
According to the Facebook docs, app requests are sent to users by POSTs to the Graph API. See the "Create" section here:
https://developers.facebook.com/docs/reference/api/user/#apprequests
Spring Social Facebook has a GraphApi class with two methods for sending POSTs, "publish()" which tries to extract an id from the response and "post()" which doesn't:
http://static.springsource.org/spring-social-facebook/docs/1.0.x/api/org/springframework/social/facebook/api/GraphApi.html
So you may need to make a call along the lines of:
Map<String, Object> requestData = new HashMap<String, Object>();
requestData.put("message", "My app's request message");
String requestId = graphApi.publish(userId, "apprequests", requestData);
Related
#Test(description = "Verify that user is able to login and get the offer details for a particular promo code", dependsOnGroups = "getAuthKey")
public void verify_offers_with_login_with_promo_code() {
Map<String, String> headers = InputRequestHelper.setHeaders("auth_api_key", auth_api_key);
**// Have to remove the below set path parameters later in the code**
requestSpecification.pathParam("promocode", "1909");
Response response = InputRequestHelper.createGetRequest(requestSpecification, captor,
Constants.OFFER_PROMOCODE_PATH, headers, "com.dhani/schemas/offers/offersPromocode.json");
CommonHelper.writeRequestAndResponseInReport(writer.toString(), response.prettyPrint());
JSONObject jsonObject = new JSONObject(response.getBody().asString());
AssertionHelper.assertNotNull(ParseDynamicJson.getKey(jsonObject, "data"), "data");
AssertionHelper.assertFieldValue(ParseDynamicJson.getKey(jsonObject, "message"), "success", "message");
}
There is no way remove config in RequestSpecification --> shouldn't re-use this. You have to create new instance of this class for every request.
Similar situation here: https://stackoverflow.com/a/69569031/7574461
I am new to spring and creating backend using spring and oauth 2 so far I was able to implement outh2 with spring and I can able to get access and refresh token:
localhost:8082/oauth/token
and response i am getting :
{
"access_token": "2b57cd84-c1fb-493e-88b0-e3da2ae66c77",
"token_type": "bearer",
"refresh_token": "db9e5e33-4878-4a31-8037-b7ad0107b82a",
"expires_in": 43199,
"scope": "read write"
}
and on user registration i am trying to get access and refresh token on behalf of user, for which i have done implementation like below (i have added this snippet inside user controller userRegistration method after getting user object request from mobile side):
final String clientId = PropertiesReader.getInstance().getProperty("client1");
final String clientSecret = PropertiesReader.getInstance().getProperty("client1password");
final Map<String, String> params = new HashMap<String, String>();
params.put("grant_type", "password");
params.put("client_id", clientId);
params.put("username", userObj.getUsername());
params.put("password", dummyPwd);
final Response response = RestAssured
.given()
.auth()
.preemptive()
.basic(clientId, clientSecret)
.and()
.with()
.params(params)
.when()
.post(PropertiesReader.getInstance()
.getProperty("oauthurl"));
if (CustomValidation.checkStringIsNotEmpty(response
.asString())) {
return ClientResponse.setResponse(
response.asString(), HttpStatus.OK);
} else {
return ClientResponse.setResponse(PropertiesReader
.getInstance().getProperty("wentwrong"),
HttpStatus.INTERNAL_SERVER_ERROR);
}
and i am getting response :
{"access_token":"00bfd552-c7eb-48ff-8f2bfd5cd24869be",
"token_type":"bearer",
"refresh_token":"f88be427-ea6e-4cad-8dc5-01d37e4cfdbc",
"expires_in":299,
"scope":"update read write",
"date":1599982652000,
"deviceDetailsSaved":false,
"firstname":"test",
"role":"USER",
"name":"test test",
"mobile":"8169280313",
"avatar":"1.svg",
"email":"test1#mail.com",
"lastname":"test"}
What i want to know is there any other proper way to get oauth tokens and append in user object after registration?. As of now this implementation is for only front end client (android) so thats why i kept client details static. Any Suggestion will helpful.
I am using keycloak for authentication in my spring application, how can I set some attribute for a user.
I have already added a custom mapper on admin console.
Please have a look below attached screen shot,in user section there is the tab where you can set the attributes
Now question will be how you will access those user attributes through code?
So here is the code which can be use to access user attributes .
HttpServletRequest httpRequest = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
KeycloakSecurityContext securityContext = (KeycloakSecurityContext) httpRequest.getAttribute(KeycloakSecurityContext.class.getName());
AccessToken accessToken = securityContext.getToken();
if(null != accessToken ){
Map<String, Object> otherClaims = accessToken.getOtherClaims() ;
tgtToken = securityContext.getTokenString();
String firstUserAtt = otherClaims.get("First_User_Attribute").toString();
String secondUserAtt = otherClaims.get("Second_User_Attribute").toString();
}
Note - First_User_Attribute,Second_User_Attribute are the key you declare in the keycloak's user attribute section.
I am trying to create a simple app on the app engine where users log
in through their Google account, and then it adds an event to their
calendar.
And I am using Java along with Eclipse for this. I have found a simple
code online:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Create an instance of GoogleOAuthParameters
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
oauthParameters.setScope("http://docs.google.com/feeds/");
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(
new OAuthHmacSha1Signer());
// Remember the token secret that we stashed? Let's get it back
// now. We need to add it to oauthParameters
String oauthTokenSecret = (String) req.getSession().getAttribute(
"oauthTokenSecret");
oauthParameters.setOAuthTokenSecret(oauthTokenSecret);
// The query string should contain the oauth token, so we can just
// pass the query string to our helper object to correctly
// parse and add the parameters to our instance of oauthParameters
oauthHelper.getOAuthParametersFromCallback(req.getQueryString(),
oauthParameters);
try {
// Now that we have all the OAuth parameters we need, we can
// generate an access token and access token secret. These
// are the values we want to keep around, as they are
// valid for all API calls in the future until a user revokes
// our access.
String accessToken = oauthHelper.getAccessToken(oauthParameters);
String accessTokenSecret = oauthParameters.getOAuthTokenSecret();
// In a real application, we want to redirect the user to a new
// servlet that makes API calls. For the safe of clarity and simplicity,
// we'll just reuse this servlet for making API calls.
oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(CONSUMER_SECRET);
// This is interesting: we set the OAuth token and the token secret
// to the values extracted by oauthHelper earlier. These values are
// already in scope in this example code, but they can be populated
// from reading from the datastore or some other persistence mechanism.
oauthParameters.setOAuthToken(accessToken);
oauthParameters.setOAuthTokenSecret(accessTokenSecret);
oauthParameters.setOAuthCallback("http://www.facebook.com");
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
// Create an instance of the DocsService to make API calls
DocsService client = new DocsService("Malware Inc.");
// Use our newly built oauthParameters
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full");
DocumentListFeed resultFeed = client.getFeed(feedUrl,
DocumentListFeed.class);
for (DocumentListEntry entry : resultFeed.getEntries()) {
resp.getWriter().println(entry.getTitle().getPlainText());
}
} catch (OAuthException e) {
// Something went wrong. Usually, you'll end up here if we have invalid
// oauth tokens
resp.getWriter().println("Here is the problem");
//Server shows 500 problem
} catch (ServiceException e) {
// Handle this exception
}
}
I have registered my application and added the KEY and Secret above
the function, but when I deploy it to the app engine it gives a 500
server error.
Could someone post a simple java program that uses gdata and oauth to
log in a Google user and print the contacts on the screen?
Thanks.
-Manoj
I was facing the same problem, and it took me a while to figure it out.
Actually, the problem is that your are missing some parts in the OAuth authorization process.
As you may know, it a 3-legged process:
Get an unauthorized request token
Authorize the request token
Exchange the authorized request token for an access token and make calls to Google Data with it.
In your case, you are doing step 3 directly.
So before you can call the servlet you described above, and effectively retrieve user's Google Data,
the user must have grant access to your application, by browsing to an authorization URL from his web browser.
You need a first servlet , for example accessible at http://yourapp.com/RequestAccess
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(YOUR_CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(YOUR_CONSUMER_SECRET);
OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();
GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
oauthParameters.setScope(FEED_SCOPE);
try {
oauthHelper.getUnauthorizedRequestToken(oauthParameters);
//GET THE UNAUTHORIZED TOKENS
String oauthRequestToken = oauthParameters.getOAuthToken();
String oauthTokenSecret = oauthParameters.getOAuthTokenSecret();
//SAVE THEM SOMEWEHERE (FOR EXAMPLE IN THE SESSION LIKE YOU DID)
// ....
//GET THE AUHTORIZATION URL
String authorizationURL= oauthHelper.createUserAuthorizationUrl(oauthParameters);
// YOU NOW HAVE THE AUHTORIZATION URL, SEND IT BACK TO THE USER SOMEHOW
// ( FOR EXAMPLE BY REDIRECTING THE REQUEST TO THAT URL)
// ...
} catch (OAuthException e1) {
LOGGER.error("error while getting unauthorized request token '{}' ", e1);
}
}
Once the user has navigate to that URL, and grant acces, you can now call your second servlet and it should work.
More info can be found on Google OAuth page here
Hope it helps!
I'm new to JAX-WS and there's a thing which I don't understand.
There's a ton of tutorials available on how to set up JAX-WS security, but in pretty much all cases BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are stored in some .xml file(depending on the container I believe) - they are "hardcoded" that is. And that's what I don't get. How can I authenticate a web service client by comparing BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY with a user name and password that's in a database? I tried setting BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY on the client side like this:
ShopingCartService scs = new ShopingCartService(wsdlURL, name);
ShopingCart sc = scs.getShopingCartPort();
Map<String, Object> requestContext = ((BindingProvider)sc).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, userName);
requestContext.put(BindingProvider.PASSWORD_PROPERTY, password);
sc.someFunctionCall();
And then, on the server side retrieving like this:
#Resource
WebServiceContext wsContext;
#WebMethod
public void someFunctionCall() {
MessageContext mc = wsContext.getMessageContext();
mc.get(BindingProvider.USERNAME_PROPERTY);
mc.get(BindingProvider.PASSWORD_PROPERTY);
}
But I always get null, I didn't set up anything in xml, web service works just fine, except I can't get those variables :(
I'm running both on java 1.6, tomcat 6 and JAX-WS.
Any help with authenticating users with passwords from a database is greatly appreciated,
Thanks.
I think you are looking for JAX-WS authentication in application level, not HTTP basic in server level. See following complete example :
Application Authentication with JAX-WS
On the web service client site, just put your “username” and “password” into request header.
Map<String, Object> req_ctx = ((BindingProvider)port).getRequestContext();
req_ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, WS_URL);
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Username", Collections.singletonList("someUser"));
headers.put("Password", Collections.singletonList("somePass"));
req_ctx.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
On the web service server site, get the request header parameters via WebServiceContext.
#Resource
WebServiceContext wsctx;
#WebMethod
public String method() {
MessageContext mctx = wsctx.getMessageContext();
Map http_headers = (Map) mctx.get(MessageContext.HTTP_REQUEST_HEADERS);
List userList = (List) http_headers.get("Username");
List passList = (List) http_headers.get("Password");
//...
BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are matching HTTP Basic Authentication mechanism that enable authentication process at the HTTP level and not at the application nor servlet level.
Basically, only the HTTP server will know the username and the password (and eventually application according to HTTP/application server specification, such with Apache/PHP).
With Tomcat/Java, add a login config BASIC in your web.xml and appropriate security-constraint/security-roles (roles that will be later associated to users/groups of real users).
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>YourRealm</realm-name>
</login-config>
Then, connect the realm at the HTTP server (or application server) level with the appropriate user repository. For tomcat you may look at JAASRealm, JDBCRealm or DataSourceRealm that may suit your needs.
http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html
I had the same problem, and found the solution here :
http://www.mastertheboss.com/web-interfaces/336-jax-ws-basic-authentication.html?start=1
good luck
For an example using both, authentication on application level and HTTP Basic Authentication see one of my previous posts.
I was face-off a similar situation, I need to provide to my WS: Username, Password and WSS Password Type.
I was initially using the "Http Basic Auth" (as #ahoge), I tried to use the #Philipp-Dev 's ref. too. I didn't get a success solution.
After a little deep search at google, I found this post:
https://stackoverflow.com/a/3117841/1223901
And there was my problem solution
I hope this can help to anyone else, like helps to me.
Rgds,
iVieL
In your client SOAP handler you need to set javax.xml.ws.security.auth.username and javax.xml.ws.security.auth.password property as follow:
public class ClientHandler implements SOAPHandler<SOAPMessageContext>{
public boolean handleMessage(final SOAPMessageContext soapMessageContext)
{
final Boolean outInd = (Boolean)soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outInd.booleanValue())
{
try
{
soapMessageContext.put("javax.xml.ws.security.auth.username", <ClientUserName>);
soapMessageContext.put("javax.xml.ws.security.auth.password", <ClientPassword>);
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
return true;
}
}
If you put the username and password at clientside into the request this way:
URL url = new URL("http://localhost:8080/myapplication?wsdl");
MyWebService webservice = new MyWebServiceImplService(url).getMyWebServiceImplPort();
Map<String, Object> requestContext = ((BindingProvider) webservice).getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "myusername");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "mypassword");
and call your webservice
String response = webservice.someMethodAtMyWebservice("test");
Then you can read the Basic Authentication string like this at the server side (you have to add some checks and do some exceptionhandling):
#Resource
WebServiceContext webserviceContext;
public void someMethodAtMyWebservice(String parameter) {
MessageContext messageContext = webserviceContext.getMessageContext();
Map<String, ?> httpRequestHeaders = (Map<String, ?>) messageContext.get(MessageContext.HTTP_REQUEST_HEADERS);
List<?> authorizationList = (List<?>) httpRequestHeaders.get("Authorization");
if (authorizationList != null && !authorizationList.isEmpty()) {
String basicString = (String) authorizationList.get(0);
String encodedBasicString = basicString.substring("Basic ".length());
String decoded = new String(Base64.getDecoder().decode(encodedBasicString), StandardCharsets.UTF_8);
String[] splitter = decoded.split(":");
String usernameFromBasicAuth = splitter[0];
String passwordFromBasicAuth = splitter[1];
}