Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 重新加载Jwt安全的spring Boot React应用程序时出现错误401(和配置问题)_Java_Reactjs_Spring_Spring Boot_Jwt - Fatal编程技术网

Java 重新加载Jwt安全的spring Boot React应用程序时出现错误401(和配置问题)

Java 重新加载Jwt安全的spring Boot React应用程序时出现错误401(和配置问题),java,reactjs,spring,spring-boot,jwt,Java,Reactjs,Spring,Spring Boot,Jwt,我正在学习spring boot和react。我已经成功地学会了如何使用前端maven插件将两者结合起来。JWT也可以工作(当令牌处于活动状态时,至少有一个api调用返回我想要的内容,当我设置快速过期时间时返回错误)。但是反应路线的工作很奇怪。我怀疑需要从web安全配置java文件中排除什么。如果我排除太多,我不会看到主页。我想我已经找到了解决方案,但现在重新加载不起作用。你能帮我找出这里出了什么问题吗?我希望JWT能够为api工作,并且我希望能够访问页面并重新加载它们。 我的网站安全配置: @

我正在学习spring boot和react。我已经成功地学会了如何使用前端maven插件将两者结合起来。JWT也可以工作(当令牌处于活动状态时,至少有一个api调用返回我想要的内容,当我设置快速过期时间时返回错误)。但是反应路线的工作很奇怪。我怀疑需要从web安全配置java文件中排除什么。如果我排除太多,我不会看到主页。我想我已经找到了解决方案,但现在重新加载不起作用。你能帮我找出这里出了什么问题吗?我希望JWT能够为api工作,并且我希望能够访问页面并重新加载它们。 我的网站安全配置:

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

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private UserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}

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

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
            // dont authenticate this particular request
            .authorizeRequests().antMatchers("/authenticate", "/", "/public/**", "/static/**/*", "/login").permitAll().
            // all other requests need to be authenticated
                anyRequest().authenticated().and().
            // make sure we use stateless session; session won't be used to
            // store user's state.
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

我找到了这个文件,它允许将404解析为索引:

package kr.ac.korea.sans.jwtlogin.config;

import java.io.IOException;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.core.Ordered;

@Configuration
public class WebConfig implements WebMvcConfigurer {

     @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.setOrder(Ordered.LOWEST_PRECEDENCE);
            registry.addViewController("/**").setViewName("forward:/index.html");
        }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**/*")
                .addResourceLocations("classpath:/static/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        Resource requestedResource = location.createRelative(resourcePath);
                        return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/static/index.html");
                    }
                });
    }
}
身份验证服务:

import axios from 'axios'

class AuthenticationService {

    executeJwtAuthenticationService(username, password) {
        return axios.post('http://localhost:8090/authenticate', {
            username,
            password
        })
    }

    executeHelloService() {
        console.log("===executeHelloService===")
        return axios.get('http://localhost:8090/hello');        
    }

    registerSuccessfulLoginForJwt(username, token) {
        console.log("===registerSuccessfulLoginForJwt===")
        localStorage.setItem('token', token);
        localStorage.setItem('authenticatedUser', username);
        this.setupAxiosInterceptors();
    }

    createJWTToken(token) {
        return 'Bearer ' + token
    }

    setupAxiosInterceptors() {
        axios.interceptors.request.use(
            config => {
                const token = localStorage.getItem('token');
                if (token) {
                    config.headers['Authorization'] = 'Bearer ' + token;
                }
                return config;
            },
            error => {
                Promise.reject(error)
            });
    }

    logout() {
        localStorage.removeItem("authenticatedUser");
        localStorage.removeItem("token");
    }

    isUserLoggedIn() {

        const token = localStorage.getItem('token');
        console.log("===UserloggedInCheck===");
        console.log(token);

        if (token) {
            return true;
        }
        return false;
    }

    getLoggedInUserName() {
        let user = localStorage.getItem('authenticatedUser');
        if(user===null) return '';
        return user;
    }


}

export default new AuthenticationService()
My Package.json:

{
  "name": "jwt-login-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "axios": "^0.19.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "set PORT=4200 && 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:8090",
  "homepage": "."
}
资源及物业:

server.port=8090
jwt.secret=godaejwt
spring.mvc.static-path-pattern = /**.* --this is for the WebConfig

您的问题很可能与react脚本使用的代理有关。如果您在与前端不同的端口上调用后端(即后端在:8080上运行,前端在:80上运行),那么您将得到401s。如果这可能是您的问题,请回答,我将把它转化为您如何解决此问题的答案。我在package.json中设置了代理,我认为正确。。。还有参考资料中的8090端口…请参阅更新的主要问题正文尽管我认为其中一个配置文件中有问题…您能否说,我是否正确排除了所有内容?您的问题很可能与react脚本使用的代理有关。如果您在与前端不同的端口上调用后端(即后端在:8080上运行,前端在:80上运行),那么您将得到401s。如果这可能是您的问题,请回答,我将把它转化为您如何解决此问题的答案。我在package.json中设置了代理,我认为正确。。。还有参考资料中的8090端口…请参阅更新后的主要问题正文虽然我认为其中一个配置文件有问题…您能否说,我是否正确排除了所有内容?