I created a microservice project that consist of a few services. In one of these services, I added an HTTP Filter to get user id in the request header that comes from API gateway. But after adding this filter, the application gives 404 not found error. But whenever I put a breakpoint to the target endpoint, I can see the request comes sucessfully but gives 404-not found.
For 2 days, I've tried to find a solution but nothing did work. Do you have any idea why this eror occures?
My web security config
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private HttpFilter httpFilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/**")
.permitAll()
.anyRequest()
.authenticated();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(httpFilter, UsernamePasswordAuthenticationFilter.class);
}
}
HttpFilter class
#Component
public class HttpFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String userId = request.getHeader("x-auth-user-id");
if(userId !=null){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
userId,null,null
);
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
filterChain.doFilter(request,response);
}
}
LOGS
2022-04-01 00:39:49.734 DEBUG 6384 --- [nio-8080-exec-2] o.a.t.util.http.Rfc6265CookieProcessor : Cookies: Parsing b[]: JSESSIONID=F04A8A4650623E59586BA5D0B3AFFB78
2022-04-01 00:39:49.734 DEBUG 6384 --- [nio-8080-exec-2] o.a.catalina.connector.CoyoteAdapter : Requested cookie session id is F04A8A4650623E59586BA5D0B3AFFB78
2022-04-01 00:39:49.735 DEBUG 6384 --- [nio-8080-exec-2] o.a.c.authenticator.AuthenticatorBase : Security checking request GET /api/message/getAll
2022-04-01 00:39:49.735 DEBUG 6384 --- [nio-8080-exec-2] org.apache.catalina.realm.RealmBase : No applicable constraints defined
2022-04-01 00:39:49.735 DEBUG 6384 --- [nio-8080-exec-2] o.a.c.authenticator.AuthenticatorBase : Not subject to any constraint
2022-04-01 00:39:49.735 DEBUG 6384 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing GET /api/message/getAll
2022-04-01 00:39:49.735 DEBUG 6384 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=1, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]]
2022-04-01 00:39:49.735 DEBUG 6384 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=1, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]]
2022-04-01 00:39:49.736 DEBUG 6384 --- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter invocation [GET /api/message/getAll] with attributes [permitAll]
2022-04-01 00:39:49.736 DEBUG 6384 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Secured GET /api/message/getAll
2022-04-01 00:39:49.737 DEBUG 6384 --- [nio-8080-exec-2] org.apache.tomcat.util.http.Parameters : Set encoding to UTF-8
2022-04-01 00:39:49.737 DEBUG 6384 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : GET "/api/message/getAll", parameters={}
2022-04-01 00:39:49.737 DEBUG 6384 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.speakiv.socialservice.api.MessageApi#getAll()
2022-04-01 00:39:49.737 DEBUG 6384 --- [nio-8080-exec-2] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-04-01 00:39:49.738 DEBUG 6384 --- [nio-8080-exec-2] o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(494638892<open>)] for JPA transaction
2022-04-01 00:39:49.739 DEBUG 6384 --- [nio-8080-exec-2] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [org.springframework.data.jpa.repository.support.SimpleJpaRepository.findAll]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
2022-04-01 00:39:49.747 DEBUG 6384 --- [nio-8080-exec-2] o.s.jdbc.datasource.DataSourceUtils : Setting JDBC Connection [HikariProxyConnection#1484327655 wrapping com.mysql.cj.jdbc.ConnectionImpl#47fa3671] read-only
2022-04-01 00:39:49.751 DEBUG 6384 --- [nio-8080-exec-2] o.h.e.t.internal.TransactionImpl : On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
2022-04-01 00:39:49.751 DEBUG 6384 --- [nio-8080-exec-2] o.h.e.t.internal.TransactionImpl : begin
2022-04-01 00:39:49.753 DEBUG 6384 --- [nio-8080-exec-2] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle#50106ca8]
2022-04-01 00:39:49.753 DEBUG 6384 --- [nio-8080-exec-2] o.h.q.c.internal.CriteriaQueryImpl : Rendered criteria query -> select generatedAlias0 from UserMessage as generatedAlias0
2022-04-01 00:39:49.754 DEBUG 6384 --- [nio-8080-exec-2] org.hibernate.SQL : select usermessag0_.id as id1_5_, usermessag0_.date as date2_5_, usermessag0_.message as message3_5_, usermessag0_.receiver_id as receiver4_5_, usermessag0_.sender_id as sender_i5_5_ from user_messages usermessag0_
2022-04-01 00:39:49.760 DEBUG 6384 --- [nio-8080-exec-2] org.hibernate.loader.Loader : Result set row: 0
2022-04-01 00:39:49.760 DEBUG 6384 --- [nio-8080-exec-2] org.hibernate.loader.Loader : Result row: EntityKey[com.speakiv.socialservice.model.entity.UserMessage#1]
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Resolving attributes for [com.speakiv.socialservice.model.entity.UserMessage#1]
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Processing attribute `date` : value = 2022-03-28 13:46:10.319
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Attribute (`date`) - enhanced for lazy-loading? - false
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Processing attribute `message` : value = Hello world
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Attribute (`message`) - enhanced for lazy-loading? - false
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Processing attribute `receiverId` : value = 1
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Attribute (`receiverId`) - enhanced for lazy-loading? - false
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Processing attribute `senderId` : value = 1
2022-04-01 00:39:49.765 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Attribute (`senderId`) - enhanced for lazy-loading? - false
2022-04-01 00:39:49.766 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Done materializing entity [com.speakiv.socialservice.model.entity.UserMessage#1]
2022-04-01 00:39:49.766 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Resolving attributes for [com.speakiv.socialservice.model.entity.UserMessage#2]
2022-04-01 00:39:49.766 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Processing attribute `date` : value = 2022-03-28 13:46:25.956
2022-04-01 00:39:49.769 DEBUG 6384 --- [nio-8080-exec-2] o.h.engine.internal.TwoPhaseLoad : Done materializing entity [com.speakiv.socialservice.model.entity.UserMessage#13]
2022-04-01 00:39:49.769 DEBUG 6384 --- [nio-8080-exec-2] o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2022-04-01 00:39:49.769 DEBUG 6384 --- [nio-8080-exec-2] o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(494638892<open>)]
2022-04-01 00:39:49.769 DEBUG 6384 --- [nio-8080-exec-2] o.h.e.t.internal.TransactionImpl : committing
2022-04-01 00:39:49.777 DEBUG 6384 --- [nio-8080-exec-2] o.s.jdbc.datasource.DataSourceUtils : Resetting read-only flag of JDBC Connection [HikariProxyConnection#1484327655 wrapping com.mysql.cj.jdbc.ConnectionImpl#47fa3671]
2022-04-01 00:39:49.780 DEBUG 6384 --- [nio-8080-exec-2] o.s.orm.jpa.JpaTransactionManager : Not closing pre-bound JPA EntityManager after transaction
2022-04-01 00:39:49.781 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [*/*]
2022-04-01 00:39:49.781 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.servlet.view.InternalResourceView : View name 'api/message/getAll', model {dataResponse=com.speakiv.speakivcore.model.response.SuccessDataResponse#3d2c9c93, org.springframework.validation.BindingResult.dataResponse=org.springframework.validation.BeanPropertyBindingResult: 0 errors}
2022-04-01 00:39:49.781 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.servlet.view.InternalResourceView : Forwarding to [api/message/getAll]
2022-04-01 00:39:49.782 DEBUG 6384 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for GET "/api/message/api/message/getAll", parameters={}
2022-04-01 00:39:49.782 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [Classpath [META-INF/resources/], Classpath [resources/], Classpath [static/], Classpath [public/], ServletContext [/]]
2022-04-01 00:39:49.787 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2022-04-01 00:39:49.787 DEBUG 6384 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=1, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade#11a677b0]
2022-04-01 00:39:49.787 DEBUG 6384 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 404
2022-04-01 00:39:49.788 DEBUG 6384 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Disabling the response for further output
2022-04-01 00:39:49.788 DEBUG 6384 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : The Response is vehiculed using a wrapper: org.springframework.security.web.header.HeaderWriterFilter$HeaderWriterResponse
2022-04-01 00:39:49.789 DEBUG 6384 --- [nio-8080-exec-2] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-04-01 00:39:49.789 DEBUG 6384 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2022-04-01 00:39:49.790 DEBUG 6384 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=1, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade#11a677b0]
2022-04-01 00:39:49.790 DEBUG 6384 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2022-04-01 00:39:49.790 DEBUG 6384 --- [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost] : Processing ErrorPage[errorCode=0, location=/error]
2022-04-01 00:39:49.791 DEBUG 6384 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing GET /error
2022-04-01 00:39:49.792 DEBUG 6384 --- [nio-8080-exec-2] w.c.HttpSessionSecurityContextRepository : Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=1, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]]
2022-04-01 00:39:49.792 DEBUG 6384 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=1, Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[]]]
2022-04-01 00:39:49.792 DEBUG 6384 --- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : Secured GET /error
2022-04-01 00:39:49.793 DEBUG 6384 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2022-04-01 00:39:49.793 DEBUG 6384 --- [nio-8080-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2022-04-01 00:39:49.793 DEBUG 6384 --- [nio-8080-exec-2] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-04-01 00:39:49.795 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2022-04-01 00:39:49.795 DEBUG 6384 --- [nio-8080-exec-2] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Fri Apr 01 00:39:49 EET 2022, status=404, error=Not Found, path=/api/message/getAll}]
2022-04-01 00:39:49.796 DEBUG 6384 --- [nio-8080-exec-2] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-04-01 00:39:49.797 DEBUG 6384 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
2022-04-01 00:39:49.798 DEBUG 6384 --- [nio-8080-exec-2] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2022-04-01 00:39:49.798 DEBUG 6384 --- [nio-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Disabling the response for further output
2022-04-01 00:39:49.799 DEBUG 6384 --- [nio-8080-exec-2] o.a.coyote.http11.Http11InputBuffer : Before fill(): parsingHeader: [true], parsingRequestLine: [true], parsingRequestLinePhase: [0], parsingRequestLineStart: [0], byteBuffer.position(): [0], byteBuffer.limit(): [0], end: [678]
2022-04-01 00:39:49.799 DEBUG 6384 --- [nio-8080-exec-2] o.a.tomcat.util.net.SocketWrapperBase : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#2efc81a4:org.apache.tomcat.util.net.NioChannel#4fd730ea:java.nio.channels.SocketChannel[connected local=/192.168.1.110:8080 remote=/192.168.1.110:52685]], Read from buffer: [0]
2022-04-01 00:39:49.799 DEBUG 6384 --- [nio-8080-exec-2] org.apache.tomcat.util.net.NioEndpoint : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#2efc81a4:org.apache.tomcat.util.net.NioChannel#4fd730ea:java.nio.channels.SocketChannel[connected local=/192.168.1.110:8080 remote=/192.168.1.110:52685]], Read direct from socket: [0]
2022-04-01 00:39:49.799 DEBUG 6384 --- [nio-8080-exec-2] o.a.coyote.http11.Http11InputBuffer : Received []
2022-04-01 00:39:49.799 DEBUG 6384 --- [nio-8080-exec-2] o.apache.coyote.http11.Http11Processor : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#2efc81a4:org.apache.tomcat.util.net.NioChannel#4fd730ea:java.nio.channels.SocketChannel[connected local=/192.168.1.110:8080 remote=/192.168.1.110:52685]], Status in: [OPEN_READ], State out: [OPEN]
2022-04-01 00:39:49.800 DEBUG 6384 --- [nio-8080-exec-2] org.apache.tomcat.util.net.NioEndpoint : Registered read interest for [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#2efc81a4:org.apache.tomcat.util.net.NioChannel#4fd730ea:java.nio.channels.SocketChannel[connected local=/192.168.1.110:8080 remote=/192.168.1.110:52685]]
After implementing WebSecurityConfigurerAdapter class, I've faced this issue. But I tried to get current user id from request header and adding this user id in to SecurityContextHolder to access current user's id. Where am I wrong? do you have any idea?
I solved the issue. That is my mistake. I forgot to return ResponseEntity as the response. After returning ResponseEntity, the problem is solved...
Related
I have a profile update page which is supposed to show errors on the fields.
However, when I remove the value from an input field instead of getting an error below, I get 405 - Request method 'PATCH' not supported.
I have no idea what could be the problem, any advice is appreciated.
#Controller
#RequestMapping("/users")
public class UserController {
#GetMapping("/profile/update/{id}")
public String showUpdateForm(#PathVariable("id") Long id, Model model) {
ProfileUpdateServiceModel profileServiceModel = this.userService.getProfileUpdateServiceModelById(id);
ProfileUpdateBindingModel profileUpdateBindingModel = this.mapper.map(profileServiceModel, ProfileUpdateBindingModel.class);
if (!model.containsAttribute("profileUpdateBindingModel")) {
model.addAttribute("profileUpdateBindingModel", profileUpdateBindingModel);
}
// model.addAttribute("profileUpdateBindingModel", profileUpdateBindingModel);
return "update-profile";
}
#PatchMapping("/profile/update/{id}")
public String update(#PathVariable("id") Long id,
#Valid ProfileUpdateBindingModel profileUpdateBindingModel,
BindingResult br,
RedirectAttributes rAtt) {
if (br.hasErrors()) {
rAtt
.addFlashAttribute("profileUpdateBindingModel", profileUpdateBindingModel)
.addFlashAttribute("org.springframework.validation.BindingResult.profileUpdateBindingModel", br);
return "redirect:/users/profile/update/" + id;
}
return "profile";
}
profile.html:
<form
th:method="GET"
th:action="#{/users/profile/update/{id}(id=${session.currentUserId})}">
update-profile.html:
<form
th:action="#{/users/profile/update/{id}(id=*{userId})}"
th:method="PATCH"
th:object="${profileUpdateBindingModel}"
enctype="multipart/form-data">
<div class="col-sm-6">
<label class="label-align">First Name<span
class="required">*</span></label>
<input
th:field="*{firstName}"
type="text"
class="form-control"
name="name"/>
<div class="col-auto">
<small th:if="${#fields.hasErrors('firstName')}"
th:errors="*{firstName}"
id="first-nameError"
class="text-light form-text bg-danger rounded">xxx</small>
</div>
</div>
LOGS:
2022-03-06 11:57:45.050 DEBUG 9492 --- [nio-8080-exec-6] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, application/xhtml+xml, image/avif, image/webp, image/apng, application/xml;q=0.9, application/signed-exchange;v=b3;q=0.9, */*;q=0.8]
2022-03-06 11:57:45.077 DEBUG 9492 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2022-03-06 11:57:45.131 DEBUG 9492 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : GET "/css/style.css", parameters={}
2022-03-06 11:57:45.131 DEBUG 9492 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [static/], ServletContext [/]]
2022-03-06 11:57:45.135 DEBUG 9492 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2022-03-06 11:57:45.138 DEBUG 9492 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/images/undraw_profile_1.svg", parameters={}
2022-03-06 11:57:45.138 DEBUG 9492 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [static/], ServletContext [/]]
2022-03-06 11:57:45.138 DEBUG 9492 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2022-03-06 11:57:45.168 DEBUG 9492 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : GET "/images/1915.jpg", parameters={}
2022-03-06 11:57:45.169 DEBUG 9492 --- [nio-8080-exec-9] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [static/], ServletContext [/]]
2022-03-06 11:57:45.178 DEBUG 9492 --- [nio-8080-exec-9] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2022-03-06 11:57:59.981 DEBUG 9492 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : PATCH "/users/profile/update/", parameters={multipart}
2022-03-06 11:57:59.984 WARN 9492 --- [nio-8080-exec-6] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PATCH' not supported]
2022-03-06 11:57:59.984 DEBUG 9492 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Completed 405 METHOD_NOT_ALLOWED
2022-03-06 11:57:59.986 DEBUG 9492 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for POST "/error", parameters={multipart}
2022-03-06 11:57:59.986 DEBUG 9492 --- [nio-8080-exec-6] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2022-03-06 11:57:59.995 DEBUG 9492 --- [nio-8080-exec-6] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2022-03-06 11:58:00.022 DEBUG 9492 --- [nio-8080-exec-6] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 405
2022-03-06 11:58:00.077 DEBUG 9492 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : GET "/css/style.css", parameters={}
2022-03-06 11:58:00.078 DEBUG 9492 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [static/], ServletContext [/]]
2022-03-06 11:58:00.083 DEBUG 9492 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2022-03-06 11:58:00.132 DEBUG 9492 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : GET "/images/undraw_profile_1.svg", parameters={}
2022-03-06 11:58:00.134 DEBUG 9492 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [static/], ServletContext [/]]
2022-03-06 11:58:00.137 DEBUG 9492 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : Completed 200 OK
HTTP Code 405 means Method not Allowed. In your spring you are mentioning GET method but in your Form you are mentioning to submit a PATCH method.
Change your form to
<form
th:action="#{/users/profile/update/{id}(id=*{userId})}"
th:method="GET"
th:object="${profileUpdateBindingModel}"
enctype="multipart/form-data">
I'd use the pathvariable like this :
#PathVariable Long id
or like this ::
#PatchMapping(params = "/{id}", consumes = "application/json")
I am not confident about thymeleaf, but you can check this syntax[in second html page]:
th:action="#{/users/profile/update/{id}(id=*{userId})}"
As in your home.html form, you have assigned the value using $ sign but here it is in *.
Also, make sure your forms are enclosed properly with </form> tags.
I am running my application which is based java spring boot framework. basically i have more then one microservices and I want them to communicate using http rest .
but getting this error. Can you help me to resolve this error??
2022-01-10 10:31:52.834 INFO 13740 --- [ main] com.accounts.account.AccountApplication : Started AccountApplication in 53.129 seconds (JVM running for 57.978)
2022-01-10 10:31:53.259 DEBUG 13740 --- [ main] o.s.b.a.ApplicationAvailabilityBean : Application availability state LivenessState changed to CORRECT
2022-01-10 10:31:53.274 DEBUG 13740 --- [ main] o.s.b.a.ApplicationAvailabilityBean : Application availability state ReadinessState changed to ACCEPTING_TRAFFIC
2022-01-10 10:32:42.838 INFO 13740 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2022-01-10 10:32:42.838 INFO 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2022-01-10 10:32:42.839 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2022-01-10 10:32:42.840 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected AcceptHeaderLocaleResolver
2022-01-10 10:32:42.841 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected FixedThemeResolver
2022-01-10 10:32:42.848 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#72a61e61
2022-01-10 10:32:42.850 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.support.SessionFlashMapManager#742dbac8
2022-01-10 10:32:42.851 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2022-01-10 10:32:42.852 INFO 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 13 ms
2022-01-10 10:32:42.942 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : GET "/", parameters={}
2022-01-10 10:32:43.030 DEBUG 13740 --- [nio-8080-exec-1] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped to ResourceHttpRequestHandler [classpath [META-INF/resources/], classpath [resources/], classpath [static/], classpath [public/], ServletContext [/]]
2022-01-10 10:32:43.046 DEBUG 13740 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-01-10 10:32:43.069 DEBUG 13740 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Resource not found
2022-01-10 10:32:43.071 DEBUG 13740 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-01-10 10:32:43.072 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed 404 NOT_FOUND
2022-01-10 10:32:43.144 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error", parameters={}
2022-01-10 10:32:43.229 DEBUG 13740 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2022-01-10 10:32:43.231 DEBUG 13740 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-01-10 10:32:43.750 DEBUG 13740 --- [nio-8080-exec-1] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2022-01-10 10:32:43.790 DEBUG 13740 --- [nio-8080-exec-1] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2022-01-10 10:32:43.791 DEBUG 13740 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 404
From the code, it seems you are trying to retrieve an account based on the customer id. In that case, it will be #GetMapping and not #PostMapping ( at line 12). Also , in case of get, we pass the variables in the url and not in the request body.
As a coding practice, the className should start with a capital letter ( the return type of your method should be Account and not accounts )
#GetMapping("/myAccount/{id}
public Account AccountsGetAccountDetails(#PathVariable String id ) {}
I have CSRF enabled in the config, and when I try to make a POST request to an authenticated endpoint without a CSRF token in header or cookie (the very first request), Spring returns an error response with status code but no response body (header CONTENT-LENGTH is 0). I have this problem in one of my projects, but I tried to reproduce the behavior with a simpler setup.
HelloController.java
#RestController
public class HelloController {
#PostMapping("/hello/")
public String hello() {
return "Hello World";
}
}
SecurityConfig.java
#EnableWebSecurity
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomAccessDeniedHandler customAccessDeniedHandler;
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated();
http.exceptionHandling().accessDeniedHandler(customAccessDeniedHandler);
}
}
CustomAccessDeniedHandler.java
#Component
#Slf4j
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
#Override public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
String errorMessage = accessDeniedException.getMessage();
log.error("Access Denied - {}", errorMessage);
response.sendError(HttpStatus.FORBIDDEN.value(), errorMessage);
}
}
I'm aware that with this setup, CSRF is enabled by default.
I also customized the AccessDeniedHandler because I want Spring to spit out more specific error message when it's working as intended.
When I use curl -i -X POST http://localhost:8080/hello/, Spring returns HTTP/1.1 403 with empty response. However, if I remove the line http.authorizeRequests().anyRequest().authenticated(); in SecurityConfig and start the same request above, there's an error message like normal behavior.
{
"timestamp":"2021-07-10T23:06:28.172+00:00",
"status":403,
"error":"Forbidden",
"message":"Could not verify the provided CSRF token because your session was not found.",
"path":"/hello/"
}
I have searched for similar questions but no one has answered why response.sendError() doesn't work when .anyRequest().authenticated() is present with the condition of missing CSRF token. The workaround seems to be using response.setStatus() and response.getWriter().write() to build the error message from scratch. Is it an expected behavior or am I missing something?
Update debug log
2021-07-10 17:52:23.933 DEBUG 24250 --- [nio-8080-exec-1] org.apache.tomcat.util.http.Parameters : Set query string encoding to UTF-8
2021-07-10 17:52:23.939 DEBUG 24250 --- [nio-8080-exec-1] o.a.c.authenticator.AuthenticatorBase : Security checking request POST /hello/
2021-07-10 17:52:23.939 DEBUG 24250 --- [nio-8080-exec-1] org.apache.catalina.realm.RealmBase : No applicable constraints defined
2021-07-10 17:52:23.944 DEBUG 24250 --- [nio-8080-exec-1] o.a.c.a.jaspic.AuthConfigFactoryImpl : Loading persistent provider registrations from [/tmp/tomcat.8080.144327633803357340/conf/jaspic-providers.xml]
2021-07-10 17:52:23.945 DEBUG 24250 --- [nio-8080-exec-1] o.a.c.authenticator.AuthenticatorBase : Not subject to any constraint
2021-07-10 17:52:23.949 INFO 24250 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-07-10 17:52:23.949 INFO 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-07-10 17:52:23.949 DEBUG 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2021-07-10 17:52:23.950 DEBUG 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected AcceptHeaderLocaleResolver
2021-07-10 17:52:23.950 DEBUG 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected FixedThemeResolver
2021-07-10 17:52:23.951 DEBUG 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator#5acdab24
2021-07-10 17:52:23.951 DEBUG 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Detected org.springframework.web.servlet.support.SessionFlashMapManager#589cd2b7
2021-07-10 17:52:23.952 DEBUG 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2021-07-10 17:52:23.952 INFO 24250 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
2021-07-10 17:52:23.967 DEBUG 24250 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing POST /hello/
2021-07-10 17:52:23.974 DEBUG 24250 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2021-07-10 17:52:23.978 DEBUG 24250 --- [nio-8080-exec-1] org.apache.tomcat.util.http.Parameters : Set encoding to UTF-8
2021-07-10 17:52:23.993 DEBUG 24250 --- [nio-8080-exec-1] o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost:8080/hello/
2021-07-10 17:52:23.994 ERROR 24250 --- [nio-8080-exec-1] i.l.s.CustomAccessDeniedHandler : Access Denied - Could not verify the provided CSRF token because your session was not found.
2021-07-10 17:52:23.997 DEBUG 24250 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-07-10 17:52:23.999 DEBUG 24250 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-07-10 17:52:24.000 DEBUG 24250 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2021-07-10 17:52:24.000 DEBUG 24250 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost] : Processing ErrorPage[errorCode=0, location=/error]
2021-07-10 17:52:24.005 DEBUG 24250 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing POST /error
2021-07-10 17:52:24.005 DEBUG 24250 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2021-07-10 17:52:24.008 DEBUG 24250 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2021-07-10 17:52:24.018 DEBUG 24250 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [POST /error] with attributes [authenticated]
2021-07-10 17:52:24.021 DEBUG 24250 --- [nio-8080-exec-1] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access
2021-07-10 17:52:24.021 DEBUG 24250 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-07-10 17:52:24.021 DEBUG 24250 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-07-10 17:52:24.021 DEBUG 24250 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2021-07-10 17:52:24.022 DEBUG 24250 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Disabling the response for further output
2021-07-10 17:52:24.027 DEBUG 24250 --- [nio-8080-exec-1] o.a.coyote.http11.Http11InputBuffer : Before fill(): parsingHeader: [true], parsingRequestLine: [true], parsingRequestLinePhase: [0], parsingRequestLineStart: [0], byteBuffer.position(): [0], byteBuffer.limit(): [0], end: [85]
2021-07-10 17:52:24.028 DEBUG 24250 --- [nio-8080-exec-1] o.a.tomcat.util.net.SocketWrapperBase : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#5287597f:org.apache.tomcat.util.net.NioChannel#7d5d9d3:java.nio.channels.SocketChannel[connected local=/127.0.0.1:8080 remote=/127.0.0.1:38824]], Read from buffer: [0]
2021-07-10 17:52:24.029 DEBUG 24250 --- [nio-8080-exec-1] o.apache.coyote.http11.Http11Processor : Error parsing HTTP request header
java.io.EOFException: null
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1345) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1255) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:799) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:359) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:261) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
2021-07-10 17:52:24.029 DEBUG 24250 --- [nio-8080-exec-1] o.apache.coyote.http11.Http11Processor : Error state [CLOSE_CONNECTION_NOW] reported while processing request
java.io.EOFException: null
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.fillReadBuffer(NioEndpoint.java:1345) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.read(NioEndpoint.java:1255) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11InputBuffer.fill(Http11InputBuffer.java:799) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11InputBuffer.parseRequestLine(Http11InputBuffer.java:359) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:261) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.46.jar:9.0.46]
at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
2021-07-10 17:52:24.030 DEBUG 24250 --- [nio-8080-exec-1] o.apache.coyote.http11.Http11Processor : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#5287597f:org.apache.tomcat.util.net.NioChannel#7d5d9d3:java.nio.channels.SocketChannel[connected local=/127.0.0.1:8080 remote=/127.0.0.1:38824]], Status in: [OPEN_READ], State out: [CLOSED]
2021-07-10 17:52:24.031 DEBUG 24250 --- [nio-8080-exec-1] o.apache.tomcat.util.threads.LimitLatch : Counting down[http-nio-8080-exec-1] latch=1
2021-07-10 17:52:24.031 DEBUG 24250 --- [nio-8080-exec-1] org.apache.tomcat.util.net.NioEndpoint : Calling [org.apache.tomcat.util.net.NioEndpoint#68245ebc].closeSocket([org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#5287597f:org.apache.tomcat.util.net.NioChannel#7d5d9d3:java.nio.channels.SocketChannel[connected local=/127.0.0.1:8080 remote=/127.0.0.1:38824]])
Have a look at the log you've given:
o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [POST /error] with attributes [authenticated]
The .anyRequest().authenticated() is blocking the access to the default /error page. If you configure in such a way that it permits this specific path, it can process as you expected.
You can do this by simply adding this:
.antMatchers("/error").permitAll()
In fact, you can allow all the urls you want if you declare a list of urls you want to allow and set that to the antMatchers parameter.
I am using spring boot 2.1.7 Release and trying to create a simple rest application . Somehow this RestController is not detected by the request from third party vandor application while is detected by curl commend from same host and soapUI.
#RestController
public class SendController {
private static final Logger log = LoggerFactory.getLogger(SendController.class);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
#PostMapping("/Message")
public ResponseEntity SendMessage(#RequestBody String body, HttpMethod method,
HttpServletRequest request, HttpServletResponse response) throws URISyntaxException {
log.info("SendMessage method of SendController invoked");
response.setStatus(200);
}
The controller is pretty simple. I have removed all codes for simple test.
current application.properties
server.port=8444
server.ssl.key-store-type=JKS
server.ssl.key-store=Message.jks
server.ssl.key-store-password=Pwd123
server.ssl.key-alias=Message
server.ssl.key-password=Pwd123
# To enable request logging - RequestLoggingFilterConfig
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
logging.file=Message-Send.log
logging.level.tomcat=DEBUG
logging.level.org.springframework.web=DEBUG
debug=true
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.suffix=.log
server.tomcat.accesslog.prefix=message_access_log
server.tomcat.accesslog.file-date-format=.yyyy-MM-dd
server.tomcat.accesslog.directory=/logs
server.connection-timeout=1200000
server.tomcat.maxKeepAliveRequests=1
server.max-http-header-size==8KB
server.tomcat.uri-encoding=UTF-8
logging.level.org.apache.tomcat=DEBUG
logging.level.org.apache.catalina=DEBUG
spring.http.log-request-details=true
logging.level.root=DEBUG
I can see the logs
DEBUG 25377 --- [https-jsse-nio-8444-Acceptor] o.apache.tomcat.util.threads.LimitLatch : Counting up[https-jsse-nio-8444-Acceptor] latch=1
DEBUG 25377 --- [https-jsse-nio-8444-exec-5] o.a.tomcat.util.net.SecureNioChannel : The SNI host name extracted for connection [java.nio.channels.SocketChannel[connected local=/123.456.78.90:8444 remote=/123.456.78.90:55079]] was [null]
DEBUG 25377 --- [https-jsse-nio-8444-exec-8] o.a.tomcat.util.net.SocketWrapperBase : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#4dacb2:org.apache.tomcat.util.net.SecureNioChannel#7829e0:java.nio.channels.SocketChannel[connected local=/123.456.78.90:8444 remote=/123.456.78.90:55079]], Read from buffer: [0]
DEBUG 25377 --- [https-jsse-nio-8444-exec-8] org.apache.tomcat.util.net.NioEndpoint : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#4dacb2:org.apache.tomcat.util.net.SecureNioChannel#7829e0:java.nio.channels.SocketChannel[connected local=/123.456.78.90:8444 remote=/123.456.78.90:55079]], Read direct from socket: [145]
DEBUG 25377 --- [https-jsse-nio-8444-exec-8] o.a.coyote.http11.Http11InputBuffer : Received [POST /SendMessage HTTP/1.1
Host: hostname:8444s
Content-Length: 13385
Connection: keep-alive
Content-Type: text/plain
]
DEBUG 25377 --- [https-jsse-nio-8444-exec-8] o.apache.coyote.http11.Http11Processor : Socket: [org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#4dacb2:org.apache.tomcat.util.net.SecureNioChannel#7829e0:java.nio.channels.SocketChannel[connected local=/123.456.78.90:8444 remote=/123.456.78.90:55079]], Status in: [OPEN_READ], State out: [CLOSED]
DEBUG 25377 --- [https-jsse-nio-8444-exec-8] org.apache.tomcat.util.net.NioEndpoint : Calling [org.apache.tomcat.util.net.NioEndpoint#1c9af63].closeSocket([org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper#4dacb2:org.apache.tomcat.util.net.SecureNioChannel#7829e0:java.nio.channels.SocketChannel[connected local=/123.456.78.90:8444 remote=/123.456.78.90:55079]])
java.lang.Exception: null
at org.apache.tomcat.util.net.NioEndpoint$NioSocketWrapper.doClose(NioEndpoint.java:1165) [tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.util.net.SocketWrapperBase.close(SocketWrapperBase.java:394) [tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.util.net.NioEndpoint$Poller.cancelledKey(NioEndpoint.java:667) [tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.22.jar!/:9.0.22]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.22.jar!/:9.0.22]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [na:1.8.0_202]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [na:1.8.0_202]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.22.jar!/:9.0.22]
at java.lang.Thread.run(Thread.java:748) [na:1.8.0_202]
for the request that Controller was detected, I can see RequestMappingHandler maps as expected.
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.a.coyote.http11.Http11InputBuffer : Received [POST /SendMessage HTTP/1.1
User-Agent: curl/7.15.5 (x86_64-redhat-linux-gnu) libcurl/7.15.5 OpenSSL/0.9.8b zlib/1.2.3 libidn/0.6.5
Host: hostname:8444
Accept: */*
Content-Type: text/plain
Connection: Keep-Alive
Content-Length: 13516
Expect: 100-continue
]
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] org.apache.tomcat.util.http.Parameters : Set query string encoding to UTF-8
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.a.c.authenticator.AuthenticatorBase : Security checking request POST /SendMessage
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] org.apache.catalina.realm.RealmBase : No applicable constraints defined
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.a.c.a.jaspic.AuthConfigFactoryImpl : Loading persistent provider registrations from [/tmp/tomcat.4732512376857604387.8444/conf/jaspic-providers.xml]
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.a.c.authenticator.AuthenticatorBase : Not subject to any constraint
INFO 25377 --- [https-jsse-nio-8444-exec-4] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 25377 --- [https-jsse-nio-8444-exec-4] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='true': request parameters and headers will be shown which may lead to unsafe logging of potentially sensitive data
INFO 25377 --- [https-jsse-nio-8444-exec-4] o.s.web.servlet.DispatcherServlet : Completed initialization in 7 ms
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] org.apache.tomcat.util.http.Parameters : Set encoding to UTF-8
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] o.s.web.servlet.DispatcherServlet : POST "/SendMessage", parameters={}
DEBUG 25377 --- [https-jsse-nio-8444-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public void SendController.SendMessage(java.lang.String,org.springframework.http.HttpMethod,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.net.URISyntaxException
Please guide me.
I am using quite basic setting to connect facebook using spring boot and spring social, but I am getting a warning in the log and no other details:
2015-11-01 09:26:34.574 WARN 69742 --- [nio-8181-exec-1] o.s.s.connect.web.ConnectController : Exception while handling OAuth2 callback ((#3) Application does not have the capability to make this API call.). Redirecting to facebook connection status page.
My controller:
#Controller
public class UserLoginOauth {
private Facebook facebook;
#Inject
public UserLoginOauth(Facebook facebook) {
this.facebook = facebook;
}
#RequestMapping(value = "/fb")
public String connectFacebook(Model model) {
try {
if (!facebook.isAuthorized()) {
return "redirect:/connect/facebook";
}
} catch (Exception e) {
return "redirect:/connect/facebook";
}
return null;
}
and my property file:
spring.social.facebook.appId=XXX
spring.social.facebook.appSecret=YYY
spring.social.auto_connection_views=true
When I go to my /fb url, I am redirect to http://localhost:8181/connect/facebook with a button to connect to facebook
On clicking that button, it calls http://localhost:8181/connect/facebook and then redirect to https://www.facebook.com/v2.3/dialog/oauth?client_id=WWW and again it redirects to http://localhost:8181/connect/facebook?code=ddd&state=GGG
But this redirect fails with the warning message "Exception while handling OAuth2 callback", with no other information.
I enabled spring social logs, and put it below incase it helps!
2015-11-09 15:07:38.130 DEBUG 14198 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/connect/facebook]
2015-11-09 15:07:38.131 DEBUG 14198 --- [nio-8181-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /connect/facebook
2015-11-09 15:07:38.131 DEBUG 14198 --- [nio-8181-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.connect(java.lang.String,org.springframework.web.context.request.NativeWebRequest)]
2015-11-09 15:07:38.131 DEBUG 14198 --- [nio-8181-exec-3] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'connectController'
2015-11-09 15:07:38.131 DEBUG 14198 --- [nio-8181-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2015-11-09 15:07:38.132 DEBUG 14198 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.RedirectView: unnamed; URL [https://www.facebook.com/v2.3/dialog/oauth?client_id=XXX&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8181%2Fconnect%2Ffacebook&state=SSS]] in DispatcherServlet with name 'dispatcherServlet'
2015-11-09 15:07:38.132 DEBUG 14198 --- [nio-8181-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2015-11-09 15:07:38.132 DEBUG 14198 --- [nio-8181-exec-3] o.s.orm.jpa.EntityManagerFactoryUtils : Closing JPA EntityManager
2015-11-09 15:07:38.132 DEBUG 14198 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : Successfully completed request
2015-11-09 15:07:42.007 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/connect/facebook]
2015-11-09 15:07:42.007 DEBUG 14198 --- [nio-8181-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /connect/facebook
2015-11-09 15:07:42.008 DEBUG 14198 --- [nio-8181-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)]
2015-11-09 15:07:42.008 DEBUG 14198 --- [nio-8181-exec-4] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'connectController'
2015-11-09 15:07:42.008 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/connect/facebook] is: -1
2015-11-09 15:07:42.008 DEBUG 14198 --- [nio-8181-exec-4] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2015-11-09 15:07:42.009 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : Created POST request for "https://graph.facebook.com/v2.3/oauth/access_token"
2015-11-09 15:07:42.009 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : Setting request Accept header to [application/x-www-form-urlencoded, multipart/form-data, application/json, application/*+json]
2015-11-09 15:07:42.009 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : Writing [{client_id=[AAA], client_secret=[BBB], code=[CCC], redirect_uri=[http://localhost:8181/connect/facebook], grant_type=[authorization_code]}] using [org.springframework.http.converter.FormHttpMessageConverter#16aa8eeb]
2015-11-09 15:07:42.554 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : POST request for "https://graph.facebook.com/v2.3/oauth/access_token" resulted in 200 (OK)
2015-11-09 15:07:42.555 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : Reading [interface java.util.Map] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#53ab366e]
2015-11-09 15:07:42.559 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : Created GET request for "https://graph.facebook.com/v2.3/me?fields=id%2Cabout%2Cage_range%2Caddress%2Cbio%2Cbirthday%2Ccontext%2Ccover%2Ccurrency%2Cdevices%2Ceducation%2Cemail%2Cfavorite_athletes%2Cfavorite_teams%2Cfirst_name%2Cgender%2Chometown%2Cinspirational_people%2Cinstalled%2Cinstall_type%2Cis_verified%2Clanguages%2Clast_name%2Clink%2Clocale%2Clocation%2Cmeeting_for%2Cmiddle_name%2Cname%2Cname_format%2Cpolitical%2Cquotes%2Cpayment_pricepoints%2Crelationship_status%2Creligion%2Csecurity_settings%2Csignificant_other%2Csports%2Ctest_group%2Ctimezone%2Cthird_party_id%2Cupdated_time%2Cverified%2Cvideo_upload_limits%2Cviewer_can_send_gift%2Cwebsite%2Cwork"
2015-11-09 15:07:42.584 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : Setting request Accept header to [application/json, application/*+json]
2015-11-09 15:07:42.695 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.client.RestTemplate : GET request for "https://graph.facebook.com/v2.3/me?fields=id%2Cabout%2Cage_range%2Caddress%2Cbio%2Cbirthday%2Ccontext%2Ccover%2Ccurrency%2Cdevices%2Ceducation%2Cemail%2Cfavorite_athletes%2Cfavorite_teams%2Cfirst_name%2Cgender%2Chometown%2Cinspirational_people%2Cinstalled%2Cinstall_type%2Cis_verified%2Clanguages%2Clast_name%2Clink%2Clocale%2Clocation%2Cmeeting_for%2Cmiddle_name%2Cname%2Cname_format%2Cpolitical%2Cquotes%2Cpayment_pricepoints%2Crelationship_status%2Creligion%2Csecurity_settings%2Csignificant_other%2Csports%2Ctest_group%2Ctimezone%2Cthird_party_id%2Cupdated_time%2Cverified%2Cvideo_upload_limits%2Cviewer_can_send_gift%2Cwebsite%2Cwork" resulted in 400 (Bad Request); invoking error handler
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : Error from Facebook: {"error":{"message":"(#3) Application does not have the capability to make this API call.","type":"OAuthException","code":3,"fbtrace_id":"HB0Fe9k\/zM1"}}
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : Facebook error:
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : CODE : 3
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : TYPE : OAuthException
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : SUBCODE : null
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : MESSAGE : (#3) Application does not have the capability to make this API call.
2015-11-09 15:07:42.696 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : USER TITLE : null
2015-11-09 15:07:42.719 DEBUG 14198 --- [nio-8181-exec-4] o.s.s.f.api.impl.FacebookErrorHandler : USER MESSAGE: null
2015-11-09 15:07:42.719 WARN 14198 --- [nio-8181-exec-4] o.s.s.connect.web.ConnectController : Exception while handling OAuth2 callback ((#3) Application does not have the capability to make this API call.). Redirecting to facebook connection status page.
2015-11-09 15:07:42.719 DEBUG 14198 --- [nio-8181-exec-4] o.s.web.servlet.DispatcherServlet : Rendering view [org.springframework.web.servlet.view.RedirectView: unnamed; URL [/connect/facebook]] in DispatcherServlet with name 'dispatcherServlet'
extend two of spring social class ConnectResource & ConnectSupport and
override the callback_url or aplicationUrl your problem will be
resolve