Search code examples
springjwt

Generating JWT token with JwtUtil class in Spring Boot resulting in NullPointerException


trying to implement a jwt based authentication for specific end points , but not able to import many of the packages , like in security config , cant able to extend my class with extends WebSecurityConfigurerAdapter , which gives many of the built in functions , jwt dependency used for this is :

io.jsonwebtoken jjwt 0.11.0

@Configuration
@EnableWebSecurity()
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {






    **Api Authentication Entry Point** 


package com.example.demo.security;

import java.io.IOException;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {
     @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
        }
}



***JWT Util***


package com.example.demo.security;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.example.demo.model.appuser;
import com.example.demo.repo.UserRepository;

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

@Component
public class Jwtutil {
    
   private appuser user;
    @Autowired
    private UserRepository userrepo;
 
    
    
    private String secret="se5827983582085309FEE25GFW324323231313gfdgw2";
    private int expiration=900000000;
    
 
    public String generatetoken(appuser user) {
         return Jwts.builder()
        .setSubject(user.getUserName())
        .claim("authorities", user.getRoles().toString())
        .setIssuedAt(new Date())
        .setExpiration(new Date(System.currentTimeMillis() + expiration))
         .signWith(SignatureAlgorithm.HS256, secret)
        .compact();
        
    }
    
    
    public String extractusername(String token) {
        Claims claims = Jwts.parser()
                       .setSigningKey(secret)
                        .parseClaimsJws(token)
                        .getBody();
        
        System.out.println( claims);
        return claims.getSubject();
    }
    

    
    public boolean verifytoken(String token) {
        if(userrepo.findByUserName(extractusername(token))!=null) {
            return true;
        }
        return false;
        
    }
}




***WebSecurityConfig***

package com.example.demo.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.example.demo.model.Role;
import com.example.demo.service.CustomUserDetails;
import com.example.demo.service.UserDetailsServiceImpl;
@Configuration
public class WebSecurityConfig {
 

 
    @Bean
    SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
        .csrf(csrf -> csrf.disable()) 
        .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/public/login" , "/**").permitAll()
                .requestMatchers("/api/**").hasAuthority("ADMIN")
                
                .anyRequest().authenticated()
            )
        
             
            .exceptionHandling(eh -> eh.accessDeniedPage("/401"))
            .headers(headers -> headers.frameOptions().sameOrigin()) // Allow H2 console to be rendered in a frame
            // Enable form login
            .httpBasic(basic -> basic.disable()); 
            ;
        
         
        return http.build();
    }
}


***public-Controller***

package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.appuser;
import com.example.demo.repo.UserRepository;
import com.example.demo.security.Jwtutil;

@RestController
public class Publiccontroller {

    @Autowired
    private UserRepository userrepo;
    
    @Autowired
    private Jwtutil jwtutil;
    
    @PostMapping("/api/public/login")
    public ResponseEntity<Object> login(@RequestBody appuser userdetails){
       
        userdetails.setRoles(userrepo.findByUserName(userdetails.getUserName()).getRoles());
        
        System.out.println("===============" +  userdetails);
        String token= jwtutil.generatetoken(userdetails);
        return ResponseEntity.ok(token);
    }
    
    
    @GetMapping("/api/public/getuserfromtoken")
    public ResponseEntity<Object> getuser(@RequestParam ("token") String token ){
        String username = jwtutil.extractusername(token);
        return ResponseEntity.ok(username);
    }
    
    
}


***Main Method***

package com.example.demo;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.example.demo.model.Beneficiary;
import com.example.demo.model.Gender;
import com.example.demo.model.Role;

import com.example.demo.model.appuser;
import com.example.demo.repo.Beneficiaryrepository;
import com.example.demo.repo.UserRepository;

@SpringBootApplication
public class InnovatorFinalApplication {
    
     @Autowired
     private UserRepository userRepository;  
     
     @Autowired
     private Beneficiaryrepository BenRepository;
     
    public static void main(String[] args) {
        SpringApplication.run(InnovatorFinalApplication.class, args);
    }

    

       @Bean
        public CommandLineRunner dataLoader( ) {
            return args -> {
                userRepository.save(new appuser (1,  "awez", "8989898989" ,   "pass-word", "ADMIN"));
                userRepository.save(new appuser (2,  "ramesh", "098099808" ,   "pass-word",  "USER"));
                userRepository.save(new appuser (3,  "suresh", "532525326" ,   "pass-word", "ADMIN"));
                userRepository.save(new appuser (4,  "vidya", "6262624225" ,   "pass-word", "ADMIN"));
                userRepository.save(new appuser (5,  "keeti", "8989898989" ,   "pass-word",  "ADMIN"));
                userRepository.save(new appuser (6,  "sravya", "098099808" ,   "pass-word", "ADMIN"));
                userRepository.save(new appuser (7,  "Indu",   "532525326" ,     "pass-word",  "ADMIN"));
                userRepository.save(new appuser (8,  "Rajesh", "6262624225" ,  "pass-word",  "ADMIN"));
                
                BenRepository.save(new Beneficiary(1, 1234, Gender.MALE, userRepository.findById(1).get(), 2000));
                BenRepository.save(new Beneficiary(2, 13534, Gender.FEMALE, userRepository.findById(2).get(), 2013));
                BenRepository.save(new Beneficiary(3, 3524, Gender.OTHER, userRepository.findById(3).get(), 2014));
                BenRepository.save(new Beneficiary(4, 23525, Gender.MALE, userRepository.findById(4).get(), 2016));
               
            };
        }
}



***application.properties***
spring.application.name=demo
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.initialization-mode=always
spring.jpa.defer-datasource-initialization=true


++++++++++++++++++++++++++++++++++++++++++++++++


spring.application.name=Innovator-Final
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE
spring.batch.jdbc.initialize-schema=always
spring.sql.init.mode=always
spring.sql.init.username=sa
spring.sql.init.password=password
server.port=8000
jwt.secret=secretkey
jwt.token.validity=900000

logging.level.=debug



Solution

  • in class: public class MySecurityConfig extends WebSecurityConfigurerAdapter the WebSecurityConfigurerAdapter is deprecated, instead you can create class like this:

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig {
        
        @Bean
        BCryptPasswordEncoder bCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }
        
        @Bean
        SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
            http.authorizeHttpRequests(authz -> authz
                    .requestMatchers(HttpMethod.GET,"/testAPI").permitAll()
                    .requestMatchers("").permitAll()
                    .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
            return http.build();
        }
        
        @Bean
        UserDetailsService userDetailsService() {
            InMemoryUserDetailsManager userDetailsService = new 
        InMemoryUserDetailsManager();
            UserDetails userDetails = User
                    .withUsername("vinod")
                    .password(bCryptPasswordEncoder().encode("singh"))
                    .authorities("read").build();
            userDetailsService.createUser(userDetails);
            return userDetailsService;
        }
    
    }