Spring boot + Angular: несанкционированная ошибка. Сообщение - для доступа к этому ресурсу требуется полная аутентификация - PullRequest
0 голосов
/ 19 апреля 2020

Я пытаюсь создать веб-приложение с пружинной загрузкой angular и пытаюсь реализовать: Angular аутентификацию Spring Boot JWT.

Я получаю ошибку ниже, когда пытаюсь нажать ( ПОЛУЧИТЬ запрос):
http://localhost: 8080 / utilisateur / pret
http://localhost: 8080 / utilisateur / записей
http://localhost: 8080 / utilisateur / all
от почтальона:

{     
    "timestamp": "2020-04-19T02:44:32.571+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Error -> Unauthorized",
    "path": "/utilisateur/pret"

}    
{ 
    "timestamp": "2020-04-19T03:17:08.904+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Error -> Unauthorized",
    "path": "/utilisateur/attente"  
} 

Ниже мой пользовательский контроллер:

package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.entities.Utilisateur;
import com.example.demo.service.IUserService;

@RestController
@CrossOrigin("*")
@RequestMapping("/utilisateur")
public class UserController {

    @Autowired
    private IUserService userService;


    //@PreAuthorize(" hasRole('USER')")
    @GetMapping("/all")
    public List<Utilisateur> Afficherp() {
        return userService.afficherTT();

    }
    //@PreAuthorize(" hasRole('USER')")
    @GetMapping("/attente")
    public List<Utilisateur> Afficherattente() {
        return userService.afficherAttente();

    }
    //@PreAuthorize(" hasRole('USER')")
    @GetMapping("/activated")
    public List<Utilisateur> AfficherActivatedUsers() {
        return userService.allActivatedUser();

    }
    //@PreAuthorize(" hasRole('USER')")
    @GetMapping("/pret")
    public List<Utilisateur> Afficherpret() {
        return userService.afficherPret();

    }
    //@PreAuthorize(" hasRole('USER')")
    @PostMapping("/add")
    public void ajouterP(@RequestBody Utilisateur user)
    {
        userService.ajouter(user);

    }
    //@PreAuthorize(" hasRole('USER')")
    @PostMapping("/activateuser")
    public void ajouterpr(@RequestBody Utilisateur user)

    {
        userService.ajouterpr(user);

    }
    //@PreAuthorize(" hasRole('USER')")
    @DeleteMapping("/delete/{id}")
    public void supprimer(@PathVariable("id") Integer ID) {
        userService.supprime(ID);

    }
    //@PreAuthorize(" hasRole('USER')")
    @PostMapping(path = "/update")

    public void update(@RequestBody Utilisateur user) {

        try {

            this.userService.ajouter(user);

        } catch (Exception e) {

        }
    }

} 

Вот контроллер AuthRestAPI:

package com.example.demo.controller;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.message.request.LoginForm;
import com.example.demo.message.request.SignUpForm;
import com.example.demo.message.response.JwtResponse;
import com.example.demo.message.response.ResponseMessage;
import com.example.demo.entities.Role;
import com.example.demo.entities.RoleName;
import com.example.demo.entities.Utilisateur;
import com.example.demo.repo.RoleRepository;
import com.example.demo.repo.IUserRepository;
import com.example.demo.security.jwt.JwtProvider;
import com.example.demo.service.IUserService;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthRestAPIs {


    @Autowired
      AuthenticationManager authenticationManager;

      @Autowired
      IUserRepository userRepository;

      @Autowired
      RoleRepository roleRepository;

      @Autowired
      PasswordEncoder encoder;

      @Autowired
      JwtProvider jwtProvider;



      @PostMapping("/signin")
      public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginForm loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(loginRequest.getFirstName(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = jwtProvider.generateJwtToken(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();

        return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getUsername(), userDetails.getAuthorities()));
      }

      @PostMapping("/signup")
      public ResponseEntity<?> registerUser(@Valid @RequestBody SignUpForm signUpRequest) {
        if (userRepository.existsByFirstName(signUpRequest.getFirstName())) {
          return new ResponseEntity<>(new ResponseMessage("Fail -> Username is already taken!"),
              HttpStatus.BAD_REQUEST);
        }

        if (userRepository.existsByMail(signUpRequest.getMail())) {
          return new ResponseEntity<>(new ResponseMessage("Fail -> Mail is already in use!"),
              HttpStatus.BAD_REQUEST);
        }

        // Creating user's account
        Utilisateur user = new Utilisateur (signUpRequest.getFirstName(), signUpRequest.getLastName(), signUpRequest.getMail(),
            encoder.encode(signUpRequest.getPassword()));

        Set<String> strRoles = signUpRequest.getRole();
        Set<Role> roles = new HashSet<>();

        strRoles.forEach(role -> {
          switch (role) {
          case "admin":
            Role adminRole = roleRepository.findByName(RoleName.ROLE_ADMIN)
                .orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
            roles.add(adminRole);

            break;
          case "pm":
            Role pmRole = roleRepository.findByName(RoleName.ROLE_PM)
                .orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
            roles.add(pmRole);

            break;
          default:
            Role userRole = roleRepository.findByName(RoleName.ROLE_USER)
                .orElseThrow(() -> new RuntimeException("Fail! -> Cause: User Role not find."));
            roles.add(userRole);
          }
        });

        user.setRoles(roles);
        userRepository.save(user);

        return new ResponseEntity<>(new ResponseMessage("User registered successfully!"), HttpStatus.OK);
      }

}

Вот WebSecurityConfiguration:


package com.example.demo.security;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
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.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.example.demo.security.jwt.JwtAuthEntryPoint;
import com.example.demo.security.jwt.JwtAuthTokenFilter;
import com.example.demo.security.services.UserDetailsServiceImpl;


@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        prePostEnabled = true
)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthEntryPoint unauthorizedHandler;

    @Bean
    public JwtAuthTokenFilter authenticationJwtTokenFilter() {
        return new JwtAuthTokenFilter();
    }

    @Override
    public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().
                authorizeRequests()
                .antMatchers("/api/auth/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}

Ниже показано, что я получаю на консоли при запуске всего приложения:

ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "http://localhost:8080/utilisateur/all", ok: false, …} 
ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "http://localhost:8080/utilisateur/attente", ok: false, …} 
GET http://localhost:8080/utilisateur/all 401 
GET http://localhost:8080/utilisateur/attente 401
...