Приложение с React, Spring и JWT не видит страницу входа - PullRequest
0 голосов
/ 08 января 2020

Я делаю приложение с React, Spring Boot и JWT. Я использовал несколько уроков, но когда я добавляю JWT, все говорит о том, что мне нужно предоставить токен даже для страницы входа! В чем может быть проблема? Спасибо! My pom. xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>net.lacit.maprunner</groupId>
    <artifactId>map-runner</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>map-runner</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <frontend-src-dir>${project.basedir}/src/main/app</frontend-src-dir>
        <web-xml-dir>${project.basedir}/src/main/webapp/WEB-INF</web-xml-dir>
        <node.version>v12.14.0</node.version>
        <npm.version>v6.13.4</npm.version>
        <npm.output.directory>${frontend-src-dir}/build</npm.output.directory>
        <frontend-maven-plugin.version>1.8.0</frontend-maven-plugin.version>
    </properties>

    <repositories>
        <repository>
            <id>local_repo</id>
            <url>file:///${project.basedir}/local_repo</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.8.0</version>
        </dependency> 

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.oracle.jdbc</groupId>
            <artifactId>ojdbc8</artifactId>
            <version>12.2.0.1</version>
        </dependency>
    </dependencies>

    <build>
    <finalName>${project.artifactId}</finalName>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
         <plugin>
            <groupId>com.github.eirslett</groupId>
            <artifactId>frontend-maven-plugin</artifactId>
            <version>1.9.1</version>
            <configuration>
               <workingDirectory>frontend</workingDirectory>
               <installDirectory>target</installDirectory>
            </configuration>
            <executions>
               <execution>
                  <id>install node and npm</id>
                  <goals>
                     <goal>install-node-and-npm</goal>
                  </goals>
                  <configuration>
                     <nodeVersion>v12.14.0</nodeVersion>
                     <npmVersion>6.13.4</npmVersion>
                  </configuration>
               </execution>
               <execution>
                  <id>npm install</id>
                  <goals>
                     <goal>npm</goal>
                  </goals>
                  <configuration>
                     <arguments>install</arguments>
                  </configuration>
               </execution>
               <execution>
                  <id>npm run build</id>
                  <goals>
                     <goal>npm</goal>
                  </goals>
                  <configuration>
                     <arguments>run build</arguments>
                  </configuration>
               </execution>
            </executions>
         </plugin>
         <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
               <execution>
                  <phase>generate-resources</phase>
                  <configuration>
                     <target>
                        <copy todir="${project.build.directory}/classes/static">
                           <fileset dir="${project.basedir}/frontend/build" />
                        </copy>
                     </target>
                  </configuration>
                  <goals>
                     <goal>run</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
    </build>


<profiles>
        <profile>
            <id>dev</id>
            <properties>
                <activatedProperties>dev</activatedProperties>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <profile>
            <id>prod</id>
            <properties>
                <activatedProperties>prod</activatedProperties>
            </properties>
        </profile>
    </profiles>

</project>

My App. js:

import React, { Component } from 'react';
import './App.css';
import MapApp from './component/MapApp.jsx';

class App extends Component {
  render() {
    return (
      <div className="container">
        <MapApp />
      </div>
    );
  }
}

export default App;

My MapApp. js:

import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import LoginComponent from './LoginComponent';
import LogoutComponent from './LogoutComponent';
import MenuComponent from './MenuComponent';
import AuthenticatedRoute from './AuthenticatedRoute';
import Calculations from './Calculations';
import CalcTypes from './CalcTypes';
import Cluster from './Cluster';
import ArtLists from './ArtLists';
import ShopLimits from './ShopLimits';
import GroupSettings from './GroupSettings';
import ClusterSettings from './ClusterSettings';
import ColorSchema from './ColorSchema';

class MapApp extends Component {


    render() {
        return (
            <>
                <Router basename={process.env.REACT_APP_ROUTER_BASE || ''}>
                    <>
                        <MenuComponent />
                        <Switch>
                            <Route path="/" exact component={LoginComponent} />
                            <Route path="/login" exact component={LoginComponent} />
                            <AuthenticatedRoute path="/logout" exact component={LogoutComponent} />
                            <AuthenticatedRoute path="/calculations" exact component={Calculations} />
                            <AuthenticatedRoute path="/calculations/:idCalc" exact component={Cluster} />
                            <AuthenticatedRoute path="/calculations/:idCalc/:idGroup" exact component={ShopLimits} />
                            <AuthenticatedRoute path="/artlists" exact component={ArtLists} />
                            <AuthenticatedRoute path="/calculation-types" exact component={CalcTypes} />
                            <AuthenticatedRoute path="/groupsettings" exact component={GroupSettings} />
                            <AuthenticatedRoute path="/clustersettings" exact component={ClusterSettings} />
                            <AuthenticatedRoute path="/colorschemas" exact component={ColorSchema} />
                        </Switch>
                    </>
                </Router>
            </>
        )
    }
}

export default MapApp

И, если вам нужно, LoginComponent:

import React, { Component } from 'react'
import AuthenticationService from '../service/AuthenticationService';

class LoginComponent extends Component {

    constructor(props) {
        super(props)

        this.state = {
            username: '',
            password: '',
            hasLoginFailed: false,
            showSuccessMessage: false
        }
    }

    handleChange = (event) => {
        this.setState(
            {
                [event.target.name]
                    : event.target.value
            }
        )
    }

    loginClicked = () => {
        AuthenticationService
            .executeJwtAuthenticationService(this.state.username, this.state.password)
            .then((response) => {
                AuthenticationService.registerSuccessfulLoginForJwt(this.state.username, response.data.token)
                console.log(response.data.token);
                this.props.history.push(`/calculations`)
            }).catch(() => {
                this.setState({ showSuccessMessage: false })
                this.setState({ hasLoginFailed: true })
            })
    }

    render() {
        return (
            <div>
                <h1>Вход</h1>
                <div className="container">
                    {this.state.hasLoginFailed && <div className="alert alert-warning">Неверные данные</div>}
                    {this.state.showSuccessMessage && <div>Вход выполнен успешно</div>}
                    Имя пользователя: <input type="text" name="username" value={this.state.username} onChange={this.handleChange} />
                    Пароль: <input type="password" name="password" value={this.state.password} onChange={this.handleChange} />
                    <button className="btn btn-success" onClick={this.loginClicked}>Вход</button>
                </div>
            </div>
        )
    }
}

export default LoginComponent

Также мой пакет. json:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.19.0",
    "bootstrap": "^4.4.1",
    "moment": "^2.24.0",
    "react": "^16.12.0",
    "react-bootstrap": "^1.0.0-beta.16",
    "react-confirm-bootstrap": "^5.3.0",
    "react-datepicker": "^2.10.1",
    "react-datetime": "^2.16.3",
    "react-dom": "^16.12.0",
    "react-router-bootstrap": "^0.25.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.2.0",
    "react-table": "^6.10.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "proxy": "http://localhost:8080",
  "homepage": "."
}

Когда я опускаю безопасность, я могу видеть интерфейс реакции. Тем не менее, в файле конфигурации есть что-то (после экспериментов я обнаружил, что это файл конфигурации, который разрушает все), что мешает приложению получить доступ даже к базовой странице входа в систему c. Я пробовал экспериментировать с путями, ничего не работает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...