2

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>
sagar limbu
  • 1,042
  • 3
  • 18
  • 43
  • Have a look into the server response (F12 on most browsers, Network tab). The server response could contain a raw exception stacktrace, allowing you to identify the root cause. – Michal Apr 11 '18 at 06:27
  • you can see the error logs. it clearly shows error is in getPrincipal() method. and i cannot find why this error is happening. – sagar limbu Apr 11 '18 at 06:30
  • which line in your code snippets is line 145 from com.lashes.controller.AppController.java ? Most likely your SecurityContext or Authentication object is null. You may want to test these for null before accessing the .getPrincipal() method. And why would it be null? Could be because your security context is configured to "permitAll" for this controller. Or maybe no authentication had happened at all. – Michal Apr 13 '18 at 03:36
  • @Michal yes were right. i was never authenticating at all. now the question is how do i authenticate this request so that i can get username even when i call from api ? do i have implement basic authentication using oauth ? – sagar limbu Apr 15 '18 at 09:48
  • 1
    I won't be able to answer this question completely in a comment, you will need to do some reading here https://docs.spring.io/spring-security/site/docs/current/guides/html5// . The most common two options: 1) you authenticate once and an authentication filter takes care of verifying the auth state in subsequent requests. And 2) stateless where you send (e.g. basic) authentication on every request. – Michal Apr 16 '18 at 00:53

0 Answers0