Dans Spring Security, l'authentification par formulaire est utilisée par défaut et les noms de paramètres sont username et `` `password```. Si vous n'avez pas besoin d'être aussi élaboré, vous pouvez réduire la quantité de code en utilisant le mécanisme d'authentification par défaut, mais récemment, l'authentification au format JSON augmente, alors comment la personnaliser avec Spring Security J'ai essayé de découvrir diverses choses.
Les paramètres de cette authentification sont les suivants.
| Le nom du paramètre | Contenu | 
|---|---|
| adresse mail | |
| password | mot de passe | 
| tenantCode | Code locataire | 
Principal.java
@Getter
@Setter
public class Principal {
  private String email;
  private String tenantCode;
  private String password;
}
LoginUser.java
@Getter
@Setter
public class LoginUser extends org.springframework.security.core.userdetails.User{
  private long userId;
  private String userName;
  //Ajoutez toutes les autres propriétés que vous souhaitez conserver
}
CustomAuthenticationFilter.java
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  @Override
  public Authentication attemptAuthentication(HttpServletRequest request,
      HttpServletResponse response) {
    try {
      Principal principal = new ObjectMapper().readValue(request.getInputStream(),
          Principal.class);
      UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
          principal, null);
      setDetails(request, authRequest);
      return this.getAuthenticationManager().authenticate(authRequest);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  @Override
  protected void successfulAuthentication(HttpServletRequest req,
      HttpServletResponse res,
      FilterChain chain,
      Authentication auth) {
    SecurityContextHolder.getContext().setAuthentication(auth);
  }
}
CustomAuthenticationProvider.java
@Configuration
public class CustomAuthenticationProvider implements AuthenticationProvider {
  //Référentiel d'informations utilisateur
  @Autowired
  UserRepository userRepository;
  //Référentiel d'informations sur les locataires
  @Autowired
  TenantRepository tenantRepository;
  @Override
  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    //Obtenez ce qui a été passé de la classe CustomAuthenticationFilter
    Principal principal = (Principal) authentication.getPrincipal();
    if (principal == null) {
      throw new BadCredentialsException("Pas d'informations d'identification");
    }
    //Vérification de la validité du code locataire
    Tenant tenant = tenantRepository.findByTenantCode(principal.getTenantCode());
    if (tenant == null || tenant.getStatus() == 0) {
      throw new BadCredentialsException("Le locataire est invalide");
    }
        //Contrôle de validité des utilisateurs par adresse e-mail et code locataire
    User user = userRepository.findByEmailAndTenantId(principal.getEmail(), tenant.getId());
    //Lorsque les informations utilisateur n'ont pas pu être obtenues
    if (user == null) {
      throw new BadCredentialsException("L'utilisateur n'existe pas");
    }
    if (!new BCryptPasswordEncoder().matches(principal.getPassword(), user.getPassword())) {
      throw new BadCredentialsException("Votre mot de passe est incorrect");
    }
    List<GrantedAuthority> authorityList = new ArrayList<>();
    //Traitement des autorisations
        LoginUser loginUser = new LoginUser();
    loginUser.setUserId(user.getId());
    loginUser.setUserName(user.getUserName());
    return new UsernamePasswordAuthenticationToken(loginUser, principal.getPassword(),
        authorityList);
  }
  @Override
  public boolean supports(Class<?> authentication) {
    return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
  }
}
  WebSecurityConfigurerAdapter```SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  CustomAuthenticationProvider authenticationProvider;
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
    filter.setRequiresAuthenticationRequestMatcher(
        new AntPathRequestMatcher("<URL de connexion>", "POST"));
    filter.setAuthenticationManager(authenticationManagerBean());
    http
        .csrf()
        .disable()
        .authorizeRequests()
        .antMatchers("<URL qui ne nécessite pas d'authentification>")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .logout()
        .logoutRequestMatcher(
            new AntPathRequestMatcher("<URL de déconnexion>", "POST"))
        .and()
        .addFilter(filter);
  }
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
  }
}
Recommended Posts