Keep getting 401 (Authorization Required) with spring social twitter - spring

I've been trying this Spring Social Accessing Twitter Data guide. And though I've double, triple an so on checked everything I keep getting this error when I click "Connect to Twitter" button:
POST request for "https://api.twitter.com/oauth/request_token" resulted in 401 (Authorization Required); invoking error handler
Here is my code:
src/main/resources/templates/connect/twitterConnect.html
<html>
<head>
<title>Hello Twitter</title>
</head>
<body>
<h3>Connect to Twitter</h3>
<form action="/connect/twitter" method="POST">
<div class="formInfo">
<p>You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.</p>
</div>
<p><button type="submit">Connect to Twitter</button></p>
</form>
</body>
src/main/resources/templates/connect/twitterConnected.html
<html>
<head>
<title>Hello Twitter</title>
</head>
<body>
<h3>Connected to Twitter</h3>
<p>
You are now connected to your Twitter account.
Click here to see your Twitter friends.
</p>
</body>
src/main/resources/templates/hello.html
<html>
<head>
<title>Hello Twitter</title>
</head>
<body>
<h3>Hello, <span th:text="${twitterProfile.name}">Some User</span>!</h3>
<h4>These are your friends:</h4>
<ul>
<li th:each="friend:${friends}" th:text="${friend.name}">Friend</li>
</ul>
</body>
src/main/java/hello/HelloController.java
#Controller
#RequestMapping("/")
public class HelloController {
private Twitter twitter;
private ConnectionRepository connectionRepository;
#Inject
public HelloController(Twitter twitter, ConnectionRepository connectionRepository) {
this.twitter = twitter;
this.connectionRepository = connectionRepository;
}
#RequestMapping(method=RequestMethod.GET)
public String helloTwitter(Model model) {
if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
return "redirect:/connect/twitter";
}
model.addAttribute(twitter.userOperations().getUserProfile());
CursoredList<TwitterProfile> friends = twitter.friendOperations().getFriends();
model.addAttribute("friends", friends);
return "hello";
}
}
src/main/java/hello/Application.java
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
/*
* SPRING BOOTSTRAP MAIN
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

I ran into the same problem.
After some investigation I found out the problem is in the callback url. Spring social sets this to yourap/signin/twitter. For facebook and linkedin this is fine, but for some reason twitter nees a filled in callback url in the application settings as well.
So the solution: Go to your twitter application settings, and fill in a callback url (this doesn't even have to be the actual callback url your going to use, just fill in any url!). Most likely this is the cause of your problems.

What does your application.properties file look like? It should have entries for spring.social.twitter.appId and spring.social.twitter.appSecret, populated with values you get when registering your application with Twitter.
Be sure that you have those in application.properties and that there are no curly-braces around the values (the guide's text shows curly-braces, but those are meant as placeholders, not something you should actually have in application.properties).

Related

Template might not exist or might not be accessible by any of the configured Template Resolvers springboot

I have a microservice app built-in spring boot, the main module is working at 8080 port and the other module is working at 7070 port. At /clicker endpoint I'm trying to redirect to
the site which is located on this port but always when I'm using /clicker endpoint I can see an error like this. But when I try to get [http://192.168.254.115:7070] directly from the browser, everything is working fine so I think that's not because of the bad config in the application.properties.
Error resolving template [http://192.168.254.115:7070], template might not exist or might not be accessible by any of the configured Template Resolvers
This controller works at 8080 port.
#CrossOrigin(origins = "*")
public class MainController {
#RequestMapping("/")
public String index() {
return "redirect:/login";
}
#RequestMapping("/home")
public String home(){
return "home.html";
}
#CrossOrigin
#RequestMapping("/clicker")
public ModelAndView goToClicker(HttpServletRequest request) {
//http://localhost:7070/
//http://192.168.254.115:7070/
String url = "http://" + request.getServerName() + ":" + "7070";
return new ModelAndView(url);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
<link rel="stylesheet" type="text/css" th:href="#{/styles/style.css}"/>
</head>
<body>
<div class = "main">
<div class = "container">
<button type="button">CLICKER</button>
</div>
</div>
</body>
</html>
And that's the controller which works at 7070 port.
#Controller
#CrossOrigin(origins = "*")
public class ClickerController {
#CrossOrigin
#RequestMapping("/")
public String index() {
return "clicker.html";
}
}

HttpStatus 406 "not acceptable" when returning Flux<String> on Spring 4.3.7 MVC Controller to a EventSource in html page

Im trying to make a timer of how much time a page is open via spring webflux, i had made this example work on springboot but with spring mvc is not working, so i know the code does work. may i have to set up something im not aware of?
Controller:
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(){
return "home";
}
#RequestMapping(value = "/timer", method = RequestMethod.GET, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public #ResponseBody Flux<String> startTimer(){
Instant startTime = Instant.now();
return Flux.fromStream(
Stream.generate(() -> calculateTimeMethod(startTime, Instant.now()))
).delayElements(Duration.ofSeconds(1));
}
}
JSP home.jsp :
<html>
<head>
<title> Home </title>
</head>
<body>
<label> tiempo trascurrido </label>
<label id="timer"></label>
<script>
var eventSource = new EventSource("url/timer");
eventSource.onmessage = function ( event ) {
document.getElementById("timer").innerText = event.data;
};
</script>
</body>
</html>
home page load but timer doesnt start, console output shows: Failed to load resource: the server responded with a status of 406 (No Aceptable)

Handling MultipartException with Spring Boot and display error page

I have a very simple file upload set up with Spring Boot.
I was wondering if there was an easy way to display an error page when the maximum file size is exceeded.
I have uploaded a very simple example of what I'm trying to achieve on github.
Basically, the idea is to catch the MultipartException in a global Spring exception handler:
#ControllerAdvice
public class UploadExceptionHandler {
#ExceptionHandler(MultipartException.class)
public ModelAndView handleError(MultipartException exception) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error", exception.getMessage());
modelAndView.setViewName("uploadPage");
return modelAndView;
}
}
The controller which handles the file upload is really simple:
#RequestMapping("/")
public String uploadPage() {
return "uploadPage";
}
#RequestMapping(value = "/", method = RequestMethod.POST)
public String onUpload(#RequestParam MultipartFile file) {
System.out.println(file.getOriginalFilename());
return "uploadPage";
}
And the uploadPage.html thymeleaf template associated with it too:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<title>Upload</title>
</head>
<body>
<div style="color: red" th:text="${error}" th:if="${error}">
Error during upload
</div>
<form th:action="#{/}" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file"/>
<button type="submit" name="save">Submit</button>
</form>
</body>
</html>
The idea is to display an error message in the same upload page when the file is too big.
It was my understanding that one would configure Spring's MultipartResolver to resolve exceptions lazily and be able to catch those exceptions at Spring's level (MVC exception handlers) but this code does not seem to help:
#Bean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)
public StandardServletMultipartResolver multipartResolver() {
StandardServletMultipartResolver multipartResolver = new StandardServletMultipartResolver();
multipartResolver.setResolveLazily(true);
return multipartResolver;
}
So before I resort to extreme measures like a filter or extending the MultipartResolver...
Do you know a clean way to handle those exceptions with Spring MVC?
Answer
Thanks to #rossen-stoyanchev.
Here is what I ended up doing:
#RequestMapping("uploadError")
public ModelAndView onUploadError(HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("uploadPage");
modelAndView.addObject("error", request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE));
return modelAndView;
}
#Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return container -> container.addErrorPages(new ErrorPage(MultipartException.class, "/uploadError"));
}
Works like a charm and feels like an elegant solution.
I updated the project on github if someone is interested.
Many thanks!
Multipart request parsing happens before a handler is selected and hence there is no #Controller and therefore no #ControllerAdvice to speak of yet. You can use an ErrorController (see http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-error-handling) for that.
BTW you don't need #RequestParam. It's enough that the argument type is MultipartFile.

With Spring Security 3.2.0.RELEASE, how can I get the CSRF token in a page that is purely HTML with no tag libs

Today I upgraded from Spring Security 3.1.4 with the separate java config dependency, to the new 3.2.0 release which includes java config. CSRF is on by default and I know I can disable it in my overridden configure method with "http.csrf().disable()". But suppose I don't want to disable it, but I need the CSRF token on my login page where no JSP tag libs or Spring tag libs are being used.
My login page is purely HTML that I use in a Backbone app that I've generated using Yeoman. How would I go about including the CSRF token that's contained in the HttpSession in either the form or as a header so that I don't get the "Expected CSRF token not found. Has your session expired?" exception?
You can obtain the CSRF using the request attribute named _csrf as outlined in the reference. To add the CSRF to an HTML page, you will need to use JavaScript to obtain the token that needs to be included in the requests.
It is safer to return the token as a header than in the body as JSON since JSON in the body could be obtained by external domains. For example your JavaScript could request a URL processed by the following:
CsrfToken token = (CsrfToken) request.getAttribute("_csrf");
// Spring Security will allow the Token to be included in this header name
response.setHeader("X-CSRF-HEADER", token.getHeaderName());
// Spring Security will allow the token to be included in this parameter name
response.setHeader("X-CSRF-PARAM", token.getParameterName());
// this is the value of the token to be included as either a header or an HTTP parameter
response.setHeader("X-CSRF-TOKEN", token.getToken());
Your JavaScript would then obtain the header name or the parameter name and the token from the response header and add it to the login request.
Although #rob-winch is right I would suggest to take token from session. If Spring-Security generates new token in SessionManagementFilter using CsrfAuthenticationStrategy it will set it to Session but not on Request. So it is possible you will end up with wrong csrf token.
public static final String DEFAULT_CSRF_TOKEN_ATTR_NAME = HttpSessionCsrfTokenRepository.class.getName().concat(".CSRF_TOKEN");
CsrfToken sessionToken = (CsrfToken) request.getSession().getAttribute(DEFAULT_CSRF_TOKEN_ATTR_NAME);
Note: I'm using CORS and AngularJS.
NoteĀ²: I found Stateless Spring Security Part 1: Stateless CSRF protection which would be interesting to keep the AngularJS' way to handle CSRF.
Instead of using Spring Security CSRF Filter which is based on answers (especially #Rob Winch's one), I used the method described in The Login Page: Angular JS and Spring Security Part II.
In addition to this, I had to add Access-Control-Allow-Headers: ..., X-CSRF-TOKEN (due to CORS).
Actually, I find this method cleaner than adding headers to the response.
Here is the code :
HttpHeaderFilter.java
#Component("httpHeaderFilter")
public class HttpHeaderFilter extends OncePerRequestFilter {
#Autowired
private List<HttpHeaderProvider> providerList;
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
providerList.forEach(e -> e.filter(request, response));
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
response.setStatus(HttpStatus.OK.value());
}
else {
filterChain.doFilter(request, response);
}
}
}
HttpHeaderProvider.java
public interface HttpHeaderProvider {
void filter(HttpServletRequest request, HttpServletResponse response);
}
CsrfHttpHeaderProvider.java
#Component
public class CsrfHttpHeaderProvider implements HttpHeaderProvider {
#Override
public void filter(HttpServletRequest request, HttpServletResponse response) {
response.addHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "X-CSRF-TOKEN");
}
}
CsrfTokenFilter.java
#Component("csrfTokenFilter")
public class CsrfTokenFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
CsrfToken csrf = (CsrfToken)request.getAttribute(CsrfToken.class.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null && !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
}
web.xml
...
<filter>
<filter-name>httpHeaderFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>httpHeaderFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
...
security-context.xml
...
<custom-filter ref="csrfTokenFilter" after="CSRF_FILTER"/>
...
app.js
...
.run(['$http', '$cookies', function ($http, $cookies) {
$http.defaults.transformResponse.unshift(function (data, headers) {
var csrfToken = $cookies['XSRF-TOKEN'];
if (!!csrfToken) {
$http.defaults.headers.common['X-CSRF-TOKEN'] = csrfToken;
}
return data;
});
}]);
I use thymeleaf with Spring boot. I had the same problem. I diagnosed problem viewing source of returned html via browser. It should be look like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<form method="post" action="/login">
<div><label> User Name : <input type="text" name="username" /> </label></div>
<div><label> Password: <input type="password" name="password" /> </label></div>
<input type="hidden" name="_csrf" value=<!--"aaef0ba0-1c75-4434-b6cf-62c975dcc8ba"--> />
<div><input type="submit" value="Sign In" /></div>
</form>
</body>
</html>
If you can't see this html code. You may be forgot to put th: tag before name and value. <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}"> Invalid username and password. </div>
<div th:if="${param.logout}"> You have been logged out. </div>
<form th:action="#{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>

Getting error when submitting form using SpringMVC and REST

Created an online form in JSP using SpringMVC tag libraries. The controller for my form is a RESTful web service.
The RESTful web service has two calls:
(1) http://localhost:8080/myapp/applications/new
This brings up the online form in the browser (this works).
(2) http://localhost:8080/myapp/applications/create
This saves the form data to a database (handles submit). This is where it breaks.
Followed the conventions from the sample demo petclinic app which comes with the Spring Framework.
Online form:
<%# page contentType="text/html;charset=UTF-8" language="java"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<body>
<form:form modelAttribute="application" method="POST" action="create">
<table>
<tr>
<td>Name:</td>
<td><form:input path="name" size="30" maxlength="80"/></td>
</tr>
<tr>
<td>Description:</td>
<td><form:input path="description" size="30" maxlength="80"/></td>
</tr>
<tr>
<td>Image URL:</td>
<td><form:input path="imgUrl" size="30" maxlength="80"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
</html>
The RESTful web service which serves as form controller:
#Controller
#Path(ApplicationsResource.APPLICATION_URL)
public class ApplicationsResource
{
private final Logger log =
LoggerFactory.getLogger(ApplicationsResource.class);
public static final String APPLICATION_URL = "/applications";
#Autowired
private ApplicationManager applicationManager;
#Autowired
private ProfileManager profileManager;
#POST
#Path("create")
#Produces(MediaType.TEXT_HTML)
public Model getNewApplication(#Context HttpServletRequest request,
#RequestAttribute Model model)
{
Application app = new Application();
model.addAttribute("application", app);
try
{
if ("POST".equalsIgnoreCase(request.getMethod()))
{
if (app != null)
{
applicationManager.save(app);
log.info("Added application: " + app.getName());
}
else
{
log.info("Application not added");
}
}
}
catch (Exception e)
{
log.info("Exception: ", e);
throw new
WebApplicationException(Response.status(
RestError.SERVER_ERROR_HTTP_RESP).
type("application/json;charset=utf-8").
entity(new ErrorOutput(RestError.SERVER_ERROR_CODE, RestError.SERVER_ERROR_MSG, e.toString())).build());
}
return model;
}
#InitBinder
public void setAllowedFields(WebDataBinder dataBinder)
{
dataBinder.setDisallowedFields(new String[] {"id"});
}
#GET
#Path("new")
#Produces( { MediaType.TEXT_HTML })
public ModelAndView getNewApplicationForm()
{
log.info("ApplicationsResource - Inside getNewApplicationForm");
ModelAndView mv = new ModelAndView("/applications/applications_new");
mv.addObject("application", new Application());
return mv;
}
}
Exception thrown when I click on submit:
Failed executing POST /applications/create
org.jboss.resteasy.spi.BadRequestException:
Could not find message body reader for type:
interface org.springframework.ui.Model of content type:
application/x-www-form-urlencoded at
org.jboss.resteasy.core.MessageBodyParameterInjector$1
createReaderNotFound(MessageBodyParameterInjector.java:73)
Does anyone know why I am getting this exception?
Would really appreciate it if someone could help me with this issue...
Happy programming and thank you for taking the time to read this.
It was a RESTEasy problem... The fix was putting the #Form Application App inside the parameter list and prepending the domain model object's setters with #FormParam("name").
See: Integrating RESTEasy with SpringMVC
You haven't told your controller what mime types it accepts and how to map them, it needs a Reader associated with that mime type to map it and send it into your method.

Resources