3

Пишу свой первый боевой проект на Spring MVC. Есть 3 класса пользователя: Customer, Cook, Admin. Все они наследуются от User класса по связям @OneToOne. Соответственно, есть 3 контроллера. После добавления Spring Security попытался протестить методы, например GET-метод у Админа, в консоли нет ни единой ошибки, а в Swagger json выдает следующую ошибку:

{
  "timestamp": "2020-05-06T13:30:13.390+0000",
  "status": 403,
  "error": "Forbidden",
  "message": "Forbidden",
  "path": "/customer/change/password"
}
Response headers
 cache-control: no-cache, no-store, max-age=0, must-revalidate 
 connection: keep-alive 
 content-type: application/json 
 date: Wed, 06 May 2020 13:30:13 GMT 
 expires: 0 
 keep-alive: timeout=60 
 pragma: no-cache 
 transfer-encoding: chunked 
 x-content-type-options: nosniff 
 x-frame-options: DENY 
 x-xss-protection: 1; mode=block 

Я пошел в WebSecurityConfig и убрал у Customer hasRole(подумал снять ограничение по роли и запустить его метод в Swagger, но тоже самое).

WebSecurityConfig:

package com.tinychiefdelights.configs;

import com.tinychiefdelights.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    // Поля
    //
    private UserService userService;


    // Injects in SETTERS
    //
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }



    // Methods
    //
    // Тут мы переопределяем метод конфигураций
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/cook/**").hasRole("COOK");
//                .antMatchers("/customer/**").hasRole("CUSTOMER");
//                .anyRequest().authenticated()
//                .and()
//                .exceptionHandling()
//                .and()
//                .formLogin()
//                .loginPage("/login")
//                .permitAll()
//                .and()
//                .logout()
//                .permitAll();
    }


    // Тут мы переопределяем для работы с внешней БД
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
    }


    // Тут мы используем encoder для шифрования паролей
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    // Возвращаем сервис пользовател для userDetServ
    @Bean
    public UserDetailsService userDetailsService() {
        return userService;
    }
}

Для примера приведу класс Customer:

Customer:

package com.tinychiefdelights.model;

import com.fasterxml.jackson.annotation.*;
import lombok.Data;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

import javax.persistence.*;
import java.util.List;

@Data
@Entity
@Table(name = "customer", schema = "public")
public class Customer {

    public Customer() { // Пустой конструктор для Hibernate

    }


    // Поля

    // name, lastName, login, password берем от класса User через связи;

    private @Id
    @GeneratedValue
    Long id;

    @Column(name = "wallet")
    private double wallet;


    //Relationships
    //
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id", referencedColumnName = "id") // Join without Customer in User class
    @NotFound(action = NotFoundAction.IGNORE)
    private User user;

    //Лист заказов
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    @JsonIgnore // Таким образом я предотвратил рекурсию
    private List<Order> orderList;
}

CustomerService:

package com.tinychiefdelights.service;

import com.tinychiefdelights.exceptions.NotFoundException;
import com.tinychiefdelights.model.*;
import com.tinychiefdelights.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class CustomerService extends UserService {

    // Поля
    //
    // Injects in setters
    private CustomerRepository customerRepository;

    private CookRepository cookRepository;

    private UserRepository userRepository;

    private OrderRepository orderRepository;

    private DishRepository dishRepository;

    private ReviewRepository reviewRepository;



    // SETTERS
    //
    // Injects into Setters
    @Autowired
    public void setReviewRepository(ReviewRepository reviewRepository) {
        this.reviewRepository = reviewRepository;
    }

    @Autowired
    public void setDishRepository(DishRepository dishRepository) {
        this.dishRepository = dishRepository;
    }

    @Autowired
    public void setCookRepository(CookRepository cookRepository) {
        this.cookRepository = cookRepository;
    }


    @Autowired
    public void setOrderRepository(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Autowired
    public void setCustomerRepository(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }



    // Методы
    //
    // Внести деньги на счет
    public void depositMoney(Long id, double money) {
        Customer customer = customerRepository.getByIdAndUserRole(id, Role.CUSTOMER);
        try {
            customer.setWallet(customer.getWallet() + money);
            customerRepository.save(customer);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException();
        } catch (NotFoundException e) {
            throw new NotFoundException(id);
        }

    }


    // Вывести деньги со счета
    public void withdrawMoney(Long id, double money) {
        Customer customer = customerRepository.getByIdAndUserRole(id, Role.CUSTOMER);
        if (money <= customer.getWallet()) { // Делаем проверку, чтобы сумма указанная заказчиком была меньше кошелька
            customer.setWallet(customer.getWallet() - money);
            customerRepository.save(customer);
        } else {
            throw new RuntimeException("Введенная Вами сумма превышает остаток на счете!");
        }
    }


    // Оставить Отзыв
    public void setReview(String text, int rate, Long id) {
        try {
            Review review = new Review();
            review.setReview(text);
            review.setRate(rate);
            review.setCook(cookRepository.getByIdAndUserRole(id, Role.COOK));
            reviewRepository.save(review);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(e);
        }

    }


    // Сделать Заказ
    public void makeOrder(String address, String phoneNumber, Long customerId,
                          Long cookId, List<Long> dishListId, Date date) { // Сделать заказ ()

        try {
            Order order = new Order();
            order.setPhoneNumber(phoneNumber);
            order.setAddress(address);
            order.setDateOrder(date);
            order.setOrderStatus(true);
            order.setCustomer(customerRepository.getByIdAndUserRole(customerId, Role.CUSTOMER));
            order.setCook(cookRepository.getByIdAndUserRole(cookId, Role.COOK));
            /**Сделать через карзину**/
//            for (Long a: dishListId) {
//                dishList.add(dishRepository.getById(a));
//            }
//            order.setDishes(dishList);
            orderRepository.save(order);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(e);
        }
    }


    // Изменить карточку заказчика
    public Customer editCustomer(Long id, User user, double wallet) {
        Customer customer = customerRepository.getByIdAndUserRole(id, Role.CUSTOMER);
        try {

            customer.setUser(user);
            customer.setWallet(wallet);
            return customerRepository.save(customer);

        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException();
        } catch (Exception e) {
            throw new NotFoundException(id);
        }
    }


    // Отменить заказ
    public void cancelOrder(Long id) {
        Order order = orderRepository.getById(id);
        order.setOrderStatus(false); // Добавим сообщение !!!!!!!!!!!!!!!
        orderRepository.save(order);
    }
}

CustomerController:

package com.tinychiefdelights.controller;

import com.tinychiefdelights.model.*;
import com.tinychiefdelights.repository.CustomerRepository;
import com.tinychiefdelights.service.CustomerService;
import com.tinychiefdelights.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@Api(value = "Работа с Заказчиком", tags = {"Заказчик"})
@RestController
@RequestMapping("/customer")
public class CustomerController {

    //Constructor
    //
    // Injects через конструктор
    @Autowired
    public CustomerController(CustomerRepository customerRepository, CustomerService customerService, UserService userService) {
        this.customerRepository = customerRepository;
        this.customerService = customerService;
        this.userService = userService;
    }


    // Fields
    // Injects into constructor
    //
    private final CustomerRepository customerRepository;

    private final CustomerService customerService;

    private final UserService userService;


    // GET MAPPING
    //


    // POST MAPPING
    //
    // Сделать заказ
    @PostMapping("/make/order")
    public void makeOrder(String address, String phoneNumber, Long customerId,
                          Long cookId, @RequestParam List<Long> dishList, Date date) {
        customerService.makeOrder(address, phoneNumber, customerId, cookId, dishList, date);
    }


    // Оставить отзыв
    @PostMapping("/set/review")
    public void setReview(String text, int rate, Long id) {
        customerService.setReview(text, rate, id);
    }

    // PUT MAPPING
    //
    // Заказчик может редактировать свою карточку (поиск по ID)
    @PutMapping("/edit/{id}")
    Customer editCustomer(@PathVariable Long id, User user, @RequestParam double wallet) {
        return customerService.editCustomer(id, user, wallet);
    }


    // Снять деньги со своего депозита (Заказчик)
    @PutMapping("/{id}/withdraw/{money}")
    void withdrawMoney(@PathVariable Long id, @RequestParam double money) {
        customerService.withdrawMoney(id, money);
    }


    // Изменить свой пароль
    @PutMapping("/change/password")
    void changePassword(@RequestParam String login, @RequestParam String newPass) {
        userService.changePassword(login, newPass);
    }


    // Внести деньги на счет (Заказчик)
    @PutMapping("/{id}/deposit/money")
    public void depositMoney(@PathVariable Long id, @RequestParam double money) {
        customerService.depositMoney(id, money);
    }


    // Отменить Заказ
    @PutMapping("/cancel/order/{id}")
    public void cancelOrder(@PathVariable Long id){
        customerService.cancelOrder(id);
    }


    // DELETE MAPPING
    //
}

Так же класс User, от которого через связи работает Customer:

User:

package com.tinychiefdelights.model;

import io.swagger.annotations.ApiModel;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.Collection;
import java.util.Collections;

@ApiModel
@Data
@Entity
@Table(name = "pg_user", schema = "public")
public class User implements UserDetails {

    public User() { // Пустой конструктор для Hibernate

    }


    // Поля
    private @Id
    @GeneratedValue
    Long id;

    @Column(name = "login")
    private String login;

    @Size(min = 5, max = 30)
    @Column(name = "password")
    private String password;

    @Enumerated(EnumType.STRING)
    @Column(name = "role")
    private Role role;

    @Column(name = "name")
    private String name;

    @Column(name = "last_name")
    private String lastName;


    // Методы
    //
    // GrantedAuthority
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + role));
    }


    // userName == login (одно и тоже)
    @Override
    public String getUsername() {
        return login;
    }


    // Во всех флагах стоит TRUE, так как не используются
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }


    @Override
    public boolean isAccountNonLocked() {
        return true;
    }


    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }


    @Override
    public boolean isEnabled() {
        return true;
    }
    //
}

ENUM ROLE:

package com.tinychiefdelights.model;


public enum Role {

    COOK, ADMIN, CUSTOMER


}

P.S. В проекте нет Front'а вообще. Все методы я пробую в ручную через Swagger и до этого у меня все отлично работало! В чем может быть проблема?

Пробовал и без hasRole. Пробовал просто через @RolesAllowed, не помогает.

введите сюда описание изображения

3
  • Сконфигурировать нужно Spring Security и добавить Swagger в исключения, чтобы он не отбивал его по 403 ошибкам.
    – Dmitrii
    7 мая 2020 в 8:39
  • как это можно сделать? 7 мая 2020 в 8:45
  • загуглить можно)
    – Dmitrii
    7 мая 2020 в 14:32

1 ответ 1

4

Для того, чтобы пофиксить данную проблему, в WebSecurityConfig класс в метод configure в начало добавляем:

http
.cors().disable()
.csrf().disable()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.