Twitter object is always null I have taken example from twitter4j - twitter4j

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
TwitterFactory twitterFac = new TwitterFactory();
Twitter twitter = twitterFac.getInstance();
twitter.setOAuthConsumer("key", "secret");
request.getSession().setAttribute("twitter", twitter);
try
{
RequestToken requestToken = twitter.getOAuthRequestToken("http://local.your-domain.com:8080/sign-in-with-twitter/callback");
request.getSession().setAttribute("requestToken", requestToken);
System.out.println(requestToken.getAuthenticationURL());
response.sendRedirect(requestToken.getAuthenticationURL());
} catch (TwitterException e)
{
throw new ServletException(e);
}
}
}
****Then the twitter page redirects to a page of my application (CallbackServlet). All this is performed correctly.****
Then the CallbackServlet has the following doGet method:
public class CallbackServlet extends HttpServlet {
private static final long serialVersionUID = 1657390011452788111L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("oauth_token");
String verifier = request.getParameter("oauth_verifier");
try {
twitter.getOAuthAccessToken(requestToken, verifier);
request.getSession().removeAttribute("requestToken");
} catch (TwitterException e) {
throw new ServletException(e);
}
response.sendRedirect(request.getContextPath() + "/");
}
}
=============================
The CallbackServlet tries to get the twitter and requestToken saved in the LoginServlet (using the method getSession().getAttribute()). This is where the problem is: the twitter object is always null!
plz sort it out

Related

SSO between App and webview inside the app

My user signs into my app using Amazon Cognito using this plugin.
I also have a spring boot application ui, secured by cognito as well.
At some point in my app flow, i want to show a webview of the spring boot application to let the user configure additional stuff.
How do i do it without having the user sign in again?
Would it be bad practice if i created an endpoint called /login/{username}/{password} that uses the SecurityContextHolder to sign the user in and redirect to /home?
I finally got it working.
First i logged in, and made my code stop somewhere using the debugger, so i could look up the SecurityContextHolder.getContext().getAuthentication(). My Authentication object is of type OAuth2AuthenticationToken. I took a close look at it, and decided to replicate it.
I did so inside a custom AuthenticationManager, and returned my OAuth2AuthenticationToken in the overriden authenticate method.
CustomAuthenticationManager.java
#Component
public class CustomAuthenticationManager implements AuthenticationManager {
#Bean
protected PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String token = ((Jwt)authentication.getPrincipal()).getTokenValue();
if (token == null)
throw new BadCredentialsException("Invalid token");
return convertAccessToken(token);
}
public OAuth2AuthenticationToken convertAccessToken(String accessToken){
Jwt decode = Tools.parseToken(accessToken);
List<GrantedAuthority> authorities = new ArrayList<>();
for (String s : ((String[]) decode.getClaims().get("cognito:groups"))) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + s));
}
Map<String, Object> claims = decode.getClaims();
OidcIdToken oidcIdToken = new OidcIdToken(decode.getTokenValue(), decode.getIssuedAt(), decode.getExpiresAt(), claims);
DefaultOidcUser user = new DefaultOidcUser(authorities, oidcIdToken, "email");
return new OAuth2AuthenticationToken(user, authorities, "cognito");
}
}
Also i put this in a static Tools.java
public static Jwt parseToken(String accessToken) {
DecodedJWT decode = com.auth0.jwt.JWT.decode(accessToken);
HashMap<String, Object> headers = new HashMap<>();
headers.put("alg", decode.getHeaderClaim("alg").asString());
headers.put("kid", decode.getHeaderClaim("kid").asString());
HashMap<String, Object> claims = new HashMap<>();
decode.getClaims().forEach((k, v) -> {
switch(k){
case "cognito:roles":
case "cognito:groups":
claims.put(k, v.asArray(String.class));
break;
case "auth_time":
case "exp":
case "iat":
claims.put(k, v.asLong());
break;
default:
claims.put(k, v.asString());
break;
}
});
return new Jwt(accessToken, decode.getIssuedAt().toInstant(), decode.getExpiresAt().toInstant(), headers, claims);
}
Then i created two endpoints. One that is my "login page", and one that my filter goes to. So in my login page i take in an access token, store it in the sesion, then redirect to my other endpoint that pasess through the filter.
TokenLoginController.java
#Component
#RestController
public class TokenLoginController {
#GetMapping(value="/login/token/{token}")
#PermitAll
public void setSession(#PathVariable("token") String token, HttpSession session, HttpServletResponse response) throws IOException {
session.setAttribute("access_token", token);
response.sendRedirect("/login/token");
}
#GetMapping(value="/login/token")
#PermitAll
public void setSession() {
}
}
The filter extends AbstractAuthenticationProcessingFilter and looks up the access token from the session, creates the OAuth2AuthenticationToken, and authenticates with it.
StickyAuthenticationFilter.java
public class StickyAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public StickyAuthenticationFilter(String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
super(defaultFilterProcessesUrl);
setAuthenticationManager(authenticationManager);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws AuthenticationException, IOException, ServletException {
String access_token = (String)servletRequest.getSession().getAttribute("access_token");
if (access_token != null) {
JwtAuthenticationToken authRequest = new JwtAuthenticationToken(Tools.parseToken(access_token));
return getAuthenticationManager().authenticate(authRequest);
}
throw new RuntimeException("Invalid access token");
}
}
And finally, my SecurityConfig ties it all together like this:
#EnableWebSecurity
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends VaadinWebSecurity {
private final ClientRegistrationRepository clientRegistrationRepository;
public SecurityConfig(ClientRegistrationRepository clientRegistrationRepository) {
this.clientRegistrationRepository = clientRegistrationRepository;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login/token/*", "/login/token").permitAll().and()
.addFilterBefore(new StickyAuthenticationFilter("/login/token", new CustomAuthenticationManager()), BearerTokenAuthenticationFilter.class)
.oauth2ResourceServer(oauth2 -> oauth2.jwt())
.authorizeRequests()
.antMatchers("/user/**")
.authenticated();
super.configure(http);
setOAuth2LoginPage(http, "/oauth2/authorization/cognito");
http.oauth2Login(l -> l.userInfoEndpoint().userAuthoritiesMapper(userAuthoritiesMapper()));
}
#Override
public void configure(WebSecurity web) throws Exception {
// Customize your WebSecurity configuration.
super.configure(web);
}
#Bean
public GrantedAuthoritiesMapper userAuthoritiesMapper() {
return (authorities) -> {
Set<GrantedAuthority> mappedAuthorities = new HashSet<>();
Optional<OidcUserAuthority> awsAuthority = (Optional<OidcUserAuthority>) authorities.stream()
.filter(grantedAuthority -> "ROLE_USER".equals(grantedAuthority.getAuthority()))
.findFirst();
if (awsAuthority.isPresent()) {
if (awsAuthority.get().getAttributes().get("cognito:groups") != null) {
mappedAuthorities = ((JSONArray) awsAuthority.get().getAttributes().get("cognito:groups")).stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.collect(Collectors.toSet());
}
}
return mappedAuthorities;
};
}
}

GWT Upload is not working in cross domain request

I am using GWTUplaod in my application which is working fine if I don't use cross domain.But it is not working correctly in cross domain scenario.
Let me explain,
GWT Server is at IP address 5.5.5.10 and GWT Client is at IP address 5.5.5.12 , earlier while uploading I was getting error in request due to cross domain then I override servlet doPost and doGetMethod
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
try {
FlowContextManager.getInstance().setFlowId(FlowContextManager.getNextFlowId());
processCrossDomainHeaders(request, response);
super.doGet(request, response);
} catch (Exception e) {
logger.error(e);
} finally {
FlowContextManager.getInstance().setFlowId("");
}
}
#Override
protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException,
ServletException {
try {
FlowContextManager.getInstance().setFlowId(FlowContextManager.getNextFlowId());
processCrossDomainHeaders(request, response);
super.doPost(request, response);
} catch (Exception e) {
logger.error(e);
} finally {
FlowContextManager.getInstance().setFlowId("");
}
}
public void processCrossDomainHeaders(HttpServletRequest request, HttpServletResponse response) {
HttpServletResponse resp = response;
HttpServletRequest req = request;
String header = req.getHeader("Origin");
if (header != null) {
resp.addHeader("Access-Control-Allow-Origin", header);
}
resp.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
header = req.getHeader("Access-Control-Request-Headers");
if (header != null) {
resp.addHeader("Access-Control-Allow-Headers", header);
}
resp.addHeader("Access-Control-Max-Age", "100");
}
#Override
protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
resp.addHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
String header = req.getHeader("Access-Control-Request-Headers");
resp.addHeader("Access-Control-Allow-Headers", header);
resp.addHeader("Access-Control-Max-Age", "100");
super.doOptions(req, resp);
}
Now my GWTUploadServlet is extending this abstract servlet.
In my web.xml I have specified following entries
<servlet>
<servlet-name>uploadServlet</servlet-name>
<!-- This is the default servlet, it puts files in session -->
<servlet-class>com.drishti.ameyo.webclient.server.WebClientUploadServlet</servlet-class>
<init-param>
<param-name>corsDomainsRegex</param-name>
<param-value>.*</param-value>
</init-param>
</servlet>
I have referred following link
http://code.google.com/p/gwtupload/issues/detail?id=187
Request is getting successful but I am getting following error on browser console.
Blocked a frame with origin "http://10.10.10.192:8888" from accessing a frame with origin "http://10.10.10.250:8888". Protocols, domains, and ports must match. FormPanelImpl.java:32
onSubmitComplete: null SuperDevModeLogger.java:71
onSubmitComplete exception parsing response: SuperDevModeLogger.java:71
com.google.gwt.xml.client.impl.DOMParseException: Failed to parse: error on line 1 at column 1: Document is empty
at createStackTrace
at fillInStackTrace_1
at fillInStackTrace
at $fillInStackTrace
at Throwable_1
at Exception_1
at RuntimeException_1
at DOMException_1
at DOMParseException_0
at throwDOMParseException
at parseImpl_0
at $parse_3
at parse_3
at onSubmitComplete_0
at $dispatch_22
at dispatch_23
at dispatch
at dispatchEvent_1
I didn't get some good solution on it.Please help for it.

smartgwt spring servlet and uploading files

I've seen this question here before, but none of the solutions work for me.
I have a SmartGWT app with Spring MVC. This all works great, and I have working RESTful web-services.
I have a form to upload not only the file, but also some meta data as well.
There is an associated DataSource with this form:
private final String DEFAULT_FILE_UPLOAD_SERVICE_PATH = "upload";
private final String TARGET = "uploadTarget";
public FileUploadForm()
{
setEncoding(Encoding.MULTIPART);
setMethod(FormMethod.POST);
setAutoFetchData(false);
setDataSource(fileUploadDS);
setTitleOrientation(TitleOrientation.TOP);
setNumCols(1);
setColWidths("*");
uploadFileIdItem.setRequired(true);
uploadFileIdItem.setDefaultValue(0);
uploadFileIdItem.setVisible(false);
uploadFileIdItem.setShowTitle(false);
// ==========================================================================
fileUploadTypeSelectItem.setShowTitle(false);
fileUploadTypeSelectItem.setName(Constants.FILE_UPLOAD_UPLOADTYPE);
fileUploadTypeSelectItem.setPickListWidth(TEXT_SIZE);
fileUploadTypeSelectItem.setTitle(Constants.TITLE_FILE_UPLOAD_UPLOADTYPE);
fileUploadTypeSelectItem.setOptionDataSource(fileUploadTypeDS);
fileUploadTypeSelectItem.setRequired(true);
fileUploadTypeSelectItem.setDisplayField(Constants.FILE_UPLOAD_UPLOADTYPE_NAME);
fileUploadTypeSelectItem.setValueField(Constants.FILE_UPLOAD_UPLOADTYPE_ID);
fileUploadTypeSelectItem.setDataPath("fileUploadType/fileUploadTypeId");
// ==========================================================================
setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
ButtonItem uploadButton = new ButtonItem("Upload");
uploadButton.addClickHandler(new com.smartgwt.client.widgets.form.fields.events.ClickHandler()
{
#Override
public void onClick(com.smartgwt.client.widgets.form.fields.events.ClickEvent event)
{
submitForm();
}
});
FileItem uploadItem = new FileItem(Constants.FILENAME);
uploadItem.setTitle(Constants.FILENAME);
setFields(uploadFileIdItem, fileUploadTypeSelectItem, uploadItem, uploadButton);
}
So, I don't know if I need to use:
setAction(GWT.getHostPageBaseURL() + "rest/" + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
or
setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
or
setAction(GWT.getHostPageBaseURL() + DEFAULT_FILE_UPLOAD_SERVICE_PATH);
None of these seem to work, I submit my data to upload the filename, and I constantly get the HTTP 404 error.
I did not define anything extra special in the web.xml file for servlets.
Instead, the springmvc-servlet contains:
<context:component-scan base-package="com.myself.products.app.server.controller" />
And the servlet is actually defined like:
#SuppressWarnings("serial")
#Controller
#RequestMapping("/upload")
public class FileUploadServlet extends HttpServlet
{
private final Logger logger = LoggerFactory.getLogger(FileUploadServlet.class);
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.process(request, response);
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.process(request, response);
}
private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// check that we have a file upload request
if (ServletFileUpload.isMultipartContent(request))
{
processFiles(request, response);
}
}
private File tmpDir;
private static final String DESTINATION_DIR_PATH = "/files/upload";
private File destinationDir;
public void init(ServletConfig config) throws ServletException
{
super.init(config);
tmpDir = new File(((File) getServletContext().getAttribute("javax.servlet.context.tempdir")).toString());
if (!tmpDir.isDirectory())
{
throw new ServletException(tmpDir.toString() + " is not a directory");
}
logger.debug("tmpDir: " + tmpDir.toString());
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if (!destinationDir.isDirectory())
{
throw new ServletException(DESTINATION_DIR_PATH + " is not a directory");
}
}
private void processFiles(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
// create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// set the size threshold, above which content will be stored on disk
factory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
// set the temporary directory (this is where files that exceed the threshold will be stored)
factory.setRepository(tmpDir);
// create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
// parse the request
List<?> items = upload.parseRequest(request);
// process the uploaded items
Iterator<?> itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
// write the uploaded file to the application's file staging area
File file = new File(destinationDir, item.getName());
item.write(file);
}
}
catch (FileUploadException e)
{
logger.error("Error encountered while parsing the request", e);
}
catch (Exception e)
{
logger.error("Error encountered while uploading file", e);
}
}
You've seen this code before along this web-site, and several others.
I'd like to submit the file, AND data if possible, but if not, then how can I submit the form, and then metadata for it?
Any help would be much appreciated.
Simple File Upload GWT Example:
Available here:
http://www.gwtproject.org/javadoc/latest/com/google/gwt/user/client/ui/FileUpload.html
For sending Metadata along with request, need to set the hidden field to panel:
import com.google.gwt.user.client.ui.Hidden;
Hidden hidden = new Hidden();
hidden.setName("json");
hidden.setVisible(false);
hidden.setValue("simpleMetadata:testData");
panel.add(hidden);
I will suggest you to seperate saving metadata from uploding a file and have 2 forms. This is what I'm doing and it is working for me:
uploadForm.setAction(GWT.getHostPageBaseURL() + "importServiceName");
uploadForm.setEncoding(Encoding.MULTIPART);
uploadForm.setTarget(TARGET);
uploadForm.setMethod(FormMethod.POST);
fileItem = new UploadItem("file");
fileItem.setTitle("File");
fileItem.setWidth(300);
NamedFrame frame = new NamedFrame(TARGET);
frame.setWidth("1");
frame.setHeight("1");
frame.setVisible(false);
uploadForm.setItems(fileItem);
I'm using NamedFrame to be able to fetch servlet response in gwt code, but this is different story. I'm defining servler manually in web.xml

formpanel.submit does not submit the file on GWT server

i want to send a file from client to server.
My code:
Client side:
private FormPanel getFormPanel() {
if (formPanel == null) {
formPanel = new FormPanel();
formPanel.setMethod(FormPanel.METHOD_POST);
formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
formPanel.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");
formPanel.setWidget(getFlexTable_1());
System.out.println(GWT.getHostPageBaseURL() +"UploadFileServlet");
}
return formPanel;
}
In getFlexTable_1()
flexTable.setWidget(1, 1, getFileUpload());
In getFileUpload()
private FileUpload getFileUpload() {
if (fileUpload == null) {
fileUpload = new FileUpload();
fileUpload.setName("upload");
}
return fileUpload;
}
private Button getAddButton() {
if (addButton == null) {
addButton = new Button("ADD");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
formPanel.submit();
}
});
}
return addButton;
}
On server side
public class CmisFileUpload extends HttpServlet implements Servlet{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
byte[] buffer = new byte[115200];//
String fileName = null;
String mimetype = null;
String majorVersion = null;
InputStream stream = null;
System.out.println("ServletWorking Fine");
}
Now when i Choose a file and click on ADD button i cant see the output on server side for this code System.out.println("ServletWorking Fine");
The outPut of System.out.println(GWT.getHostPageBaseURL() +"UploadFileServlet"); on client side is
http://127.0.0.1:8888/UploadFileServlet
and when i use this url directly on browser i get server side output for System.out.println("ServletWorking Fine");**
Edited
I created one more web application for file upload
public class Uploadfile implements EntryPoint {
FormPanel uploadForm = new FormPanel();
public void onModuleLoad() {
HorizontalPanel horizontalPanel = new HorizontalPanel();
uploadForm.setAction(GWT.getHostPageBaseURL() +"UploadFileServlet");
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
horizontalPanel.add(uploadForm);
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
uploadForm.setWidget(panel);
FlexTable flexTable = new FlexTable();
panel.add(flexTable);
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
flexTable.setWidget(2, 3, upload);
// panel.add(upload);
// Add a 'submit' button.
Button uploadSubmitButton = new Button("Submit");
panel.add(uploadSubmitButton);
uploadSubmitButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
// TODO Auto-generated method stub
uploadForm.submit();
}
});
uploadForm.addFormHandler(new FormHandler() {
public void onSubmit(FormSubmitEvent event) {
}
public void onSubmitComplete(FormSubmitCompleteEvent event) {
Window.alert(event.getResults());
}
});
RootPanel.get().add(horizontalPanel);
}
}
Server
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
System.out.println("working fine" );
}
This code is working fine
According to me there is no difference between the codes.
Plz tell me why the formpanel.submit is not working properly.
Plz help.
Is hide() method is closing the window??? If Yes then
remove move code hide(); after formPanel.submit();
for hide() use FormHandler. for eg
uploadForm.addFormHandler(new FormHandler() {
public void onSubmitComplete(FormSubmitCompleteEvent event) {
hide();
}
public void onSubmit(FormSubmitEvent event) {
}
});
reason: The FormPanel must not be detached (i.e. removed from its parent until the submission is complete. Otherwise, notification of submission will fail.
Why you have mapped for GET method for file upload. The GET request method is serving for the url entered in browser. Remove the GET Request Map, it will work.
For the POST request map, you can use MultipartFile for RequestParam as below
protected void uploadFileAndReconcilePayout1(#RequestParam("documentUpload") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException {
//code for file working
}

How to post data and redirect to another page using GWT?

When I press a button I post some data to server and there redirect to another page.
I used RequestBuilder but it is waiting the response, and of course get it. And nothing happens, same page stays. I see RequestBuidler shouldn't be used here... What should I use to post data and be able to redirect?
In Spring
#RequestMapping(method=RequestMethod.POST, value="/ddd")
public ModelAndView processOrder(#RequestBody String orderInString, HttpSession session) throws Exception{
...
return new ModelAndView(new RedirectView("abc"));
}
In GWT
public void postData(final String data, final String url) {
RequestBuilder builder = new RequestBuilder(RequestBuilder.POST, url);
try {
builder.sendRequest(data, new RequestCallback() {
public void onError(Request request, Throwable exception) {
...
}
public void onResponseReceived(Request request,
Response response) {
if (200 == response.getStatusCode()) {
..
} else {
..
}
}
});
} catch (RequestException e) {
...
}
return;
}
FormPanel form = new FormPanel("_self");
form.setMethod(FormPanel.METHOD_GET);
Hidden params0 = new Hidden("param1", "value1");
Hidden params1 = new Hidden("param1", "value2");
Hidden params2 = new Hidden("param2", "value3");
FlowPanel panel = new FlowPanel();
panel.add(params0);
panel.add(params1);
panel.add(params2);
form.add(panel);
form.setAction(GWT.getModuleBaseURL() + "../MyServlet");
RootPanel.get().add(form);
form.submit();
Thats it. The code adds FormPanel and sends form.
Add more specifications, code, this is blur.
Since you are using Spring-mvc, you should be having something like this
private static final String newPage = "index2"; //this is resolved with view resolver
#RequestMapping(params = "action=button")
protected String getALPLicense(final RenderRequest request,
final RenderResponse response, final Model model) throws Exception {
try{
}catch{
}
return newPage; //this is your new redirected page
}