Что делать если не получается авторизоваться spring rest?

Не получается принять post запрос для авторизации пользователя. Гуглил авторизацию в Srping rest но информации толком нет, как я понял нужно как и в обычном приложении настраивать авторизацию, но все равно не выходит. Ответа от сервера в принципе нет, когда от get запроса есть.
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private MyUserDetailsService userDetailsService;



    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override

    protected void configure(HttpSecurity http) throws Exception {
        http
                    .cors()
                .and()
                    .csrf()
                .and()
                    .authorizeRequests()
                    .antMatchers(
                            "/js/**",
                            "/css/**",
                            "/images/**").permitAll()
                    .antMatchers( "/login").permitAll()
                    .antMatchers( "/registration").permitAll()
                    .antMatchers("/admin/**").hasAuthority("ADMIN")
                    .antMatchers("/student/**").permitAll()
                    .antMatchers("/teacher/**").hasAuthority("TEACHER")
                    .anyRequest()
                    .authenticated()
                .and()
                    .formLogin()
                    .loginPage("/login")
                    .failureUrl("/login?error=true")
                    .defaultSuccessUrl("/home")
                    .permitAll()
                    .usernameParameter("user_name")
                    .passwordParameter("password")
                .and()
                    .logout()
                    .permitAll()
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/login").and().exceptionHandling()
                    .accessDeniedPage("/access-denied")
                .and()
                    .sessionManagement()
                    .invalidSessionUrl("/login")
                    .maximumSessions(1)
                    .maxSessionsPreventsLogin(true);
    }

}

@Component
public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, x-requested-with");
        chain.doFilter(req, response);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

Сам запрос на реакте
const authorization = {
user_name: "admin",
password: "admin",
};
axios.post(`http://localhost:8080/login`, authorization)
.then(res => {
console.log(res);
})
  • Вопрос задан
  • 89 просмотров
Решения вопроса 1
azerphoenix
@azerphoenix Куратор тега Java
Java Software Engineer
Не лучше ли для REST использовать JWT авторизацию?
https://www.callicoder.com/spring-boot-spring-secu...
https://github.com/hantsy/springboot-jwt-sample
https://medium.com/@hantsy/protect-rest-apis-with-...
https://auth0.com/blog/implementing-jwt-authentica...
https://www.baeldung.com/spring-security-oauth-jwt
На основании этих материалов в своем проекте я реализовал JWT авторизацию
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы