Код: Выделить всё
localhost redirected you too many times
ERR_TOO_MANY_REDIRECTS
Код: Выделить всё
.authorizeHttpRequests(auth -> auth
.requestMatchers("/","/login.html","/register","/testtest.html").permitAll()
Кроме того, независимо от того, какой URL-адрес я использую, даже скажем localhost:8080/ ; или localhost:8080/testtest, меня всегда перенаправляют на login.html с ошибкой «слишком много перенаправлений». Вот несколько файлов из моего проекта:
UsersLoginDTO:
Код: Выделить всё
package com.example.DevNote.DTO;
import jakarta.validation.constraints.NotBlank;
public class UsersLoginDTO {
@NotBlank(message = "Veuillez renseigner un nom d'utilisateur")
private String username;
@NotBlank(message = "Veuillez renseigner un mot de passe")
private String password;
public @NotBlank(message = "Veuillez renseigner un nom d'utilisateur") String getUsername() {
return username;
}
public void setUsername(@NotBlank(message = "Veuillez renseigner un nom d'utilisateur") String username) {
this.username = username;
}
public @NotBlank(message = "Veuillez renseigner un mot de passe") String getPassword() {
return password;
}
public void setPassword(@NotBlank(message = "Veuillez renseigner un mot de passe") String password) {
this.password = password;
}
}
Код: Выделить всё
package com.example.DevNote.security;
public class JwtAuthenticationResponse {
private String accessToken;
private String tokenType = "Bearer";
public JwtAuthenticationResponse(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getTokenType() {
return tokenType;
}
}
Код: Выделить всё
package com.example.DevNote.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class TokenProvider {
@Value("${JWT_SECRET_KEY}")
private String secretkey;
public String generateToken(Authentication authentication) {
return JWT.create()
.withSubject(authentication.getName())
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + 86400000))
.sign(Algorithm.HMAC512(secretkey.getBytes()));
}
}
Код: Выделить всё
package com.example.DevNote.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
{
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/","/login.html", "/register","/testtest.html").permitAll()
.anyRequest().authenticated())
.formLogin(form -> form
.loginPage("/login.html")
.defaultSuccessUrl("/home", true))
.logout(logout -> logout
.logoutSuccessUrl("/login.html"));
return http.build();
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}
Код: Выделить всё
package com.example.DevNote.service;
import com.example.DevNote.DTO.UsersRegistrationDTO;
import com.example.DevNote.model.Role;
import com.example.DevNote.model.Users;
import com.example.DevNote.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserService implements UserDetailsService {
@Autowired
private UsersRepository usersRepository;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
public Users createUserTestMapping(String username, String email, String password, Role role) {
Users user = new Users(username, email, password, role);
usersRepository.save(user);
return user;
}
@Transactional
public Users createUser(UsersRegistrationDTO dto) throws Exception
{
if (usersRepository.existsByUsername(dto.getUsername()))
{
throw new Exception("Le nom d'utilisateur est déjà pris.");
}
if (usersRepository.existsByEmail(dto.getEmail()))
{
throw new Exception("L'adresse e-mail est déjà utilisée.");
}
Role defaultrole = Role.Apprenant;
String hashedPassword = passwordEncoder.encode(dto.getPassword());
Users user = new Users(dto.getUsername(), dto.getEmail(), hashedPassword, defaultrole);
usersRepository.save(user);
return user;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users user = usersRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("Utilisateur non trouvé : " + username));
List authorities = AuthorityUtils.createAuthorityList("APPRENANT", "ADMIN");
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
authorities);
}
}
Код: Выделить всё
package com.example.DevNote.controller;
import com.example.DevNote.DTO.UsersRegistrationDTO;
import com.example.DevNote.DTO.UsersLoginDTO;
import com.example.DevNote.security.JwtAuthenticationResponse;
import com.example.DevNote.security.TokenProvider;
import com.example.DevNote.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.logging.Logger;
@RestController
@RequestMapping("/api/users")
public class UsersController {
@Autowired
private UserService userService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private TokenProvider tokenProvider;
private static final Logger logger = Logger.getLogger(UsersController.class.getName());
@PostMapping("/register")
public ResponseEntity registerUser(@RequestBody @Validated UsersRegistrationDTO userdto, BindingResult bindingResult)
{
if (bindingResult.hasErrors())
{
return ResponseEntity.badRequest().body(bindingResult.getAllErrors());
}
try
{
userService.createUser(userdto);
return ResponseEntity.ok("Création du compte utilisateur réussie");
}
catch (Exception e)
{
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@PostMapping("/login")
public ResponseEntity loginUser(@RequestBody @Validated UsersLoginDTO loginDTO) {
logger.info("Attempting to login user");
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword())
);
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = tokenProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
}
@GetMapping("/login.html")
public String login(Authentication authentication) {
logger.info("Accessing the login page");
if (authentication != null && authentication.isAuthenticated()) {
return "home.html";
}
return "login.html";
}
@GetMapping("/home.html")
public String home(Authentication authentication) {
logger.info("Accessing the home page");
if (authentication != null && authentication.isAuthenticated()) {
return "home.html";
}
return "redirect:/login";
}
@GetMapping("/")
public String root() {
return "redirect:/testtest.html";
}
@GetMapping("/testtest.html")
public String testtest() {
logger.info("Accessing the testtest page");
return "testtest.html";
}
}
src/main/resources/templates/
Заранее большое спасибо
Подробнее здесь: https://stackoverflow.com/questions/785 ... gin-page-n