I want to only allow the login and token api to get the token and want to require authorization for rest of the apis using JWT tokens but I am getting error while trying the login api through postman. I am getting 401 error.
WebSecurityConfig.java class
package com.springboot.quizapp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((authz) -> authz
.requestMatchers("/login", "/token","/api/v1/auth/login").permitAll()
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
return http.build();
}
}
AuthController.java
package com.springboot.quizapp.controller;
import com.springboot.quizapp.entity.User;
import com.springboot.quizapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
@Autowired
private UserService userService;
// private JwtService jwtService;
@PostMapping("/login")
public String loginUser(@RequestBody User user) throws Exception{
return userService.authenticateUser(user);
}
@PostMapping("/register")
public int registerUser(@RequestBody User user) throws Exception{
return userService.registerUser(user);
}
}
I am getting this error while trying to hit login api:
Error screenshot