как я могу устранить ошибку почтальон 401 неавторизованный - PullRequest
0 голосов
/ 29 мая 2020

Я разрабатываю серверную часть для регистрации пользователя на моем сайте.

у меня проблема, когда я хочу проверить, работает ли мой код в почтальоне, я получаю следующую ошибку:

{
    "timestamp": "2020-05-29T13:38:13.114+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/adduser"
}

Я действительно не знаю, откуда эта ошибка, вот код конфигурации, который я поставил для весенней безопасности:

package com.app.habilitation.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure (HttpSecurity http) throws Exception {

        http.cors();
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/**").
        fullyAuthenticated().and().httpBasic();
    }

    @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("{noop}hr").roles("USER");
    }
}

, а это мой контроллер:

package com.app.habilitation.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.RestController;

import com.app.habilitation.entity.UserEntity;
import com.app.habilitation.service.UserService;

@SpringBootApplication
@RestController
@CrossOrigin(origins = "*")
public class UserController {

    private UserService userService;

    @Autowired
    public UserController (UserService theuserService) {
        userService=theuserService;
    }


    @GetMapping("/")
    public String login() {
        return "authenticaated succesfully";
    }

    @GetMapping("/getUsers") 
    public String getUsers() {
        return "users";
    }

    @PostMapping("/addUser")
    public UserEntity addUser (@RequestBody UserEntity theUser) {

        userService.save(theUser);

        return theUser;
    }
}

Я добавил перекрестное начало, чтобы попытаться устранить мою ошибку, но это не работает :( вот что я сделал, как вы могли видеть в моем контроллере:

@CrossOrigin(origins = "*")

это мой dao с использованием jpa :

package com.app.habilitation.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.app.habilitation.entity.UserEntity;

public interface UserDao extends JpaRepository<UserEntity, Integer> {



}

и это мой класс сущности:

package com.app.habilitation.entity;

import java.sql.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="ORDO_DEP_UTILISATEUR")
public class UserEntity {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="IDENTIFIANT")
    private Integer IDENTIFIANT;

    /*@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="EMPLOI") */
    @Column(name="EMPLOI")
    private Integer emploi;

    /* @ManyToOne(cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name="ENTITE") */
    @Column(name="ENTITE")
    private Integer entite;


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


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


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

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

    @Column(name="CREERPAR")
    private Integer creerpar;

    @Column(name="ANNULEPAR")
    private Integer annulepar;

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

    @Column(name="DATEEFFET")
    private Date dateeffet;


    @Column(name="DATEFIN")
    private Date datefin;

    @Column(name="CREELE")
    private Date creele;

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

    @Column(name="ANNULELE")
    private Date annulele;

    public Integer getIDENTIFIANT() {
        return IDENTIFIANT;
    }

    public void setIDENTIFIANT(Integer iDENTIFIANT) {
        IDENTIFIANT = iDENTIFIANT;
    }

    public Integer getEmploi() {
        return emploi;
    }

    public void setEmploi(Integer emploi) {
        this.emploi = emploi;
    }

    public Integer getEntite() {
        return entite;
    }

    public void setEntite(Integer entite) {
        this.entite = entite;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getMdp() {
        return mdp;
    }

    public void setMdp(String mdp) {
        this.mdp = mdp;
    }

    public String getNom() {
        return nom;
    }

    public void setNom(String nom) {
        this.nom = nom;
    }

    public String getPrenom() {
        return prenom;
    }

    public void setPrenom(String prenom) {
        this.prenom = prenom;
    }

    public Integer getCreerpar() {
        return creerpar;
    }

    public void setCreerpar(Integer creerpar) {
        this.creerpar = creerpar;
    }

    public Integer getAnnulepar() {
        return annulepar;
    }

    public void setAnnulepar(Integer annulepar) {
        this.annulepar = annulepar;
    }

    public String getStatut() {
        return statut;
    }

    public void setStatut(String statut) {
        this.statut = statut;
    }

    public Date getDateeffet() {
        return dateeffet;
    }

    public void setDateeffet(Date dateeffet) {
        this.dateeffet = dateeffet;
    }

    public Date getDatefin() {
        return datefin;
    }

    public void setDatefin(Date datefin) {
        this.datefin = datefin;
    }

    public Date getCreele() {
        return creele;
    }

    public void setCreele(Date creele) {
        this.creele = creele;
    }

    public String getMotifdedesactivation() {
        return motifdedesactivation;
    }

    public void setMotifdedesactivation(String motifdedesactivation) {
        this.motifdedesactivation = motifdedesactivation;
    }

    public Date getAnnulele() {
        return annulele;
    }

    public void setAnnulele(Date annulele) {
        this.annulele = annulele;
    }

    public UserEntity(Integer iDENTIFIANT, Integer emploi, Integer entite, String login, String mdp, String nom,
            String prenom, Integer creerpar, Integer annulepar, String statut, Date dateeffet, Date datefin,
            Date creele, String motifdedesactivation, Date annulele) {
        IDENTIFIANT = iDENTIFIANT;
        this.emploi = emploi;
        this.entite = entite;
        this.login = login;
        this.mdp = mdp;
        this.nom = nom;
        this.prenom = prenom;
        this.creerpar = creerpar;
        this.annulepar = annulepar;
        this.statut = statut;
        this.dateeffet = dateeffet;
        this.datefin = datefin;
        this.creele = creele;
        this.motifdedesactivation = motifdedesactivation;
        this.annulele = annulele;
    }

    public UserEntity() {
    }

    @Override
    public String toString() {
        return "UserEntity [IDENTIFIANT=" + IDENTIFIANT + ", emploi=" + emploi + ", entite=" + entite + ", login="
                + login + ", mdp=" + mdp + ", nom=" + nom + ", prenom=" + prenom + ", creerpar=" + creerpar
                + ", annulepar=" + annulepar + ", statut=" + statut + ", dateeffet=" + dateeffet + ", datefin="
                + datefin + ", creele=" + creele + ", motifdedesactivation=" + motifdedesactivation + ", annulele="
                + annulele + "]";
    }



}

это мой интерфейс userService:

package com.app.habilitation.service;

import java.util.List;

import com.app.habilitation.entity.UserEntity;



public interface UserService {




    public void save (UserEntity theUser);


}

, а это мой userServiceImpl:

package com.app.habilitation.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.app.habilitation.dao.UserDao;
import com.app.habilitation.entity.UserEntity;

@Service
public class UserServiceImpl implements UserService {

    private UserDao userDao;

    @Autowired

    public UserServiceImpl (UserDao theuserDao) {

        userDao = theuserDao;
    }



    @Override
    @Transactional
    public void save(UserEntity theUser) {

        userDao.save(theUser);

    }



}

и это мое application.properties (я меняю порт 8080 на 8484, потому что другое приложение использует порт 8080, а для информации я использую oracle 10g):

spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
spring.datasource.username=nawfel       
spring.datasource.password=hr


server.port=8484

может кто-нибудь помочь мне пожалуйста?: (

1 Ответ

1 голос
/ 29 мая 2020

Попробуйте изменить код AuthenticationManagerBuilder, как указано ниже: -

 @Override
    protected void configure (AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
        .withUser("hr")
        .password("hr").roles("USER");
    }

И установите пароль для имени пользователя от почтальона. имя пользователя и пароль.

Если вы не знаете, как это сделать, перейдите по этой ссылке: - https://harperdbhelp.zendesk.com/hc/en-us/articles/115010250207-Basic-Auth-with-Postman

...