i have a form data which gets submitted to rest API by using javascript post request.
the code looks like:-
fetch(url,{
method:'POST',
headers:{
'Accept':'application/json, text/plain, */*',
'Content-type':'application/json'
},
body:JSON.stringify(transactionArr)
}).then(function (respone) {
if(respone.status==200){
alert("service sales successfully completed");
window.location.reload();
}
})
now my controller looks like this:-
@RequestMapping(value = "/createServiceBill", method = RequestMethod.POST)
public ResponseEntity<Status> createServiceBill(@RequestBody List<ServiceSales> serviceSales){
String username = AppController.getPrincipal();
serveServices.createServiceSales(serviceSales);
return new ResponseEntity<Status>(HttpStatus.OK);
}
as you can see i have a static method getPrincipal()
on another class called AppController.
and this getPrincipal
method looks like:-
public static String getPrincipal(){
String username = null;
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
if(principal instanceof UserDetails){
username = ((UserDetails)principal).getUsername();
}else {
username = principal.toString();
}
return username;
}
so i tried to debug it and the code execution freezes on line
Object principal = SecurityContextHolder.getContext()
.getAuthentication().getPrincipal();
Intellij shows application is running and nothing happens.
console on the browser prints :-
createServiceBill Failed to load resource: the server responded with a status of 500 ()
I need to get the username of the currently logged in user so that i can insert list of form data with currently logged in username.
Added Edit
my security configuration is:-
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("userDetailsService")
UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
public static final String[] PUBLIC_MATCHERS ={
"/static/css/**",
"/static/images/**",
"/",
"/login",
"/static/js/**",
"/getProductDetailsByCategory/**",
"/getProductByProductName/**",
"/getAllServiceByCategory/**",
"/getServicesByServiceName/**",
"/createServiceBill/**",
"/getProductReport/**"
};
@Override
public void configure(WebSecurity web) throws Exception{
web.ignoring()
.antMatchers("/createBill","/getExcelReport",
"/createServiceBill","/getProductReport");
}
protected void configure(HttpSecurity http) throws Exception{
String admin = "admin";
System.out.println(passwordEncoder().encode(admin));
http.authorizeRequests().antMatchers(PUBLIC_MATCHERS)
.permitAll().anyRequest().authenticated();
http.authorizeRequests()
.antMatchers("/admin/**")
.access("hasRole('ROLE_ADMIN')")
.and()
.formLogin()
.loginPage("/login").failureUrl("/login?error")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/admin")
.and().logout().logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.and().csrf()
.and().exceptionHandling().accessDeniedPage("/403");
}
@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder= new BCryptPasswordEncoder();
return encoder;
}
}
error shown :-
<!doctype html><html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1><hr class="line" /><p><b>Type</b> Exception Report</p><p><b>Message</b> Request processing failed; nested exception is java.lang.NullPointerException</p><p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
</pre><p><b>Root Cause</b></p><pre>java.lang.NullPointerException
com.lashes.controller.AppController.getPrincipal(AppController.java:145)
com.lashes.controller.ServiceBillingController.createServiceBill(ServiceBillingController.java:62)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208)
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177)
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
</pre><p><b>Note</b> The full stack trace of the root cause is available in the server logs.</p><hr class="line" /><h3>Apache Tomcat/8.5.14</h3></body></html>