Как добавить авторизацию в приложение Spring Boot?JAVA

Программисты JAVA общаются здесь
Anonymous
Как добавить авторизацию в приложение Spring Boot?

Сообщение Anonymous »

Я хочу разрешить только API входа и токена для получения токена и хочу требовать авторизации для остальных API с использованием токенов JWT, но я получаю сообщение об ошибке при попытке API входа в систему через почтальона. Я получаю ошибку 401.
Класс WebSecurityConfig.java

Код: Выделить всё

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);
}
}

Я получаю эту ошибку при попытке войти в API:
Снимок экрана с ошибкой

Подробнее здесь: https://stackoverflow.com/questions/787 ... pplication

Вернуться в «JAVA»