0

I have class used for authentication from which I want to call the method defined in my controller class.

when I @Autowired variable for controller class, I am getting nullPointerException for the same class.

nullPointerException_autowired

It looks like the controller is not initialized. When I initialize manually (private SubjectController sc = new SubjectController() ) I am getting nullPointerException for the repository variable which is in my controller class.

nullPointerException_manually

If I test that method directly, it's working fine.

Class for authentication:

package com.master.security;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.master.resource.LoginResource;
import com.master.rest.SubjectController;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;


public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;
    
    private JwtProperties jwtProperties;   
    
    private SubjectController sc = new SubjectController();
    
    JwtAuthenticationFilter(AuthenticationManager authenticationManager, JwtProperties jwtProperties) {
        this.authenticationManager = authenticationManager;
        this.jwtProperties = jwtProperties;
    }
    

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req,
                                                HttpServletResponse res) throws AuthenticationException {
        try {
            LoginResource loginResource = new ObjectMapper()
                    .readValue(req.getInputStream(), LoginResource.class);


            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginResource.getUsername(),
                            loginResource.getPassword(),
                            new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
  

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) {
        GrebUserDetails userDetails = ((GrebUserDetails) auth.getPrincipal());
        
        Map<String, Object> jsonResponse = new LinkedHashMap<>();
        
        String token = Jwts.builder()
                .setSubject(userDetails.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 86_400_000)) // 1 day
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecretKey().getBytes())
                .compact();

        res.addHeader("Authorization", "Bearer " + token);
        res.addHeader("Content-Type", "application/json");
        res.addHeader("userId", userDetails.getId().toString());
        
        System.out.println("Professor ID: " + sc.returnRole(userDetails.getId().intValue()));
        
        try {
            jsonResponse.put("token", token);
            jsonResponse.put("userId", userDetails.getId());
            jsonResponse.put("userRole", "P");
            
            res.getWriter().write(
                    new ObjectMapper().writeValueAsString(
                            jsonResponse
                            )
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Repository Class:

package com.master.repository;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestParam;

import com.master.entities.Professor;

@Repository
public interface ProfessorRepository extends JpaRepository<Professor, Integer>{

    List<Professor> findByName(String name);
    
    List<Professor> findAll();
    
    Professor findProfessorByIdprofessoor(int idprofessor);
    
    Professor findProfessorByUserid(int userid);
    
    List<Professor> findByFaculty(String faculty);
    
    int deleteByIdprofessoor(int idprofessor);
    
    void deleteAll();
    
    Professor findByUserid(int userid);
}

Controller class:

package com.master.rest;

import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.annotations.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.master.repository.ProfessorRepository;

@RestController
@RequestMapping("/")
public class SubjectController {
            
    @Autowired
    ProfessorRepository professorRepository;
    
    
    public String returnRole(int userId) {
        System.out.println("User id: " + userId);
        if (professorRepository.findProfessorByUserid(userId) != null) 
            return "P";
        else 
            return "S";
    }

If I add mapping and endpoint and try to test it directly, it is working

package com.master.rest;

import java.lang.annotation.ElementType;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.annotations.Target;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.master.entities.Subject;
import com.master.repository.ProfessorRepository;

@RestController
@RequestMapping("/")
public class SubjectController {
    
    @Autowired
    ProfessorRepository professorRepository;
    
    @GetMapping("/userRole")
    public String returnRole(int userId) {
        System.out.println("User id: " + userId);
        if (professorRepository.findProfessorByUserid(userId) != null) 
            return "P";
        else
            return "S";
    }

Main class:

package com.master;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;

import com.master.service.UserService;

/**
 * Hello world!
 *
 */
@SpringBootApplication
@EnableAutoConfiguration
public class App {
    
    @Autowired
        private UserService userService;

    
    public static void main( String[] args )
    {
        SpringApplication.run(App.class, args);
        System.out.println( "Started!" );               
        
    }
    
    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        userService.createAdminUser();
        System.out.print("User has been created");
    }
}
sasska94
  • 13
  • 3
  • Can you paste you main class . Looks like some problem with component scan – Umesh Sanwal Sep 30 '20 at 14:07
  • Are you getting NullPointerException when application is running and Spring did its bootstrap phase? – sigur Sep 30 '20 at 14:07
  • No, I am getting nullPointerException when I try to hit /login, more precisely when this line is executed System.out.println("Professor ID: " + sc.returnRole(userDetails.getId().intValue())); in successfulAuthentication method of JwtAuthenticationFilter class. – sasska94 Sep 30 '20 at 14:10

0 Answers0