How to set up a repository I created for Spring Security (Basic)

Asked

Viewed 27 times

1

I’m on a project and we’ll use Basic Auth of Spring Security, I would like to know how to make the configuration so that it uses the users created with my Repository.

Entity:

@Entity
public class User extends SuperEntity {
    private String name;
    private Date birth;
    private String email;
    private Integer xp;
    private Integer xpForNextLevel;
    private Integer level;
    private Integer punctuation;
    private String password;
    private String image;
    private boolean authenticated;

    public User() {
        this.xp = 0;
        this.punctuation = 0;
        this.authenticated = false;
        this.xpForNextLevel = 40;
        this.level = 0;
    }
}

Repository:

@Repository
public interface UserRepository extends SuperRepository<User> {
    User findByEmail(String email);

    List<User> findAllByDeadIsFalseOrderByPunctuationDesc();

    List<User> findAllByDeadIsFalseOrderByLevelDesc();
}

Configuration of Security:

@Configuration
@EnableWebSecurity
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .httpBasic()
                .and()
                .csrf()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .antMatchers("/**").permitAll();
    }
}

Application:

@SpringBootApplication
@Import(value = { SecurityConfiguration.class })
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

1 answer

0


I used authentication with JWT as follows:

public class CustomAuthenticationManager implements AuthenticationManager {

    @Autowired
    private UserRepository repository;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        try {
            User user = repository.findByEmail(auth.getName().toString());
            if (auth.getCredentials().toString().equals(user.getPassword())) {
                return auth;
            }
        } catch (NullPointerException e){
            throw new BadCredentialsException("Usuário não cadastrado!");
        }
        throw new BadCredentialsException("Senha incorreta");
    }

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.