Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.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 401在远程访问时尝试访问API时未经授权_Java_Spring Boot_Tomcat_Spring Security_War - Fatal编程技术网

Java 401在远程访问时尝试访问API时未经授权

Java 401在远程访问时尝试访问API时未经授权,java,spring-boot,tomcat,spring-security,war,Java,Spring Boot,Tomcat,Spring Security,War,我做了一些搜索,但在我的情况下什么都没有(或谁的解决方案)。我有一个使用SpringBoot和Tomcat9的JAVA API,当我在本地使用它时,所有这些都可以工作,但当我试图将API放在VPS上时,我无法访问它 见: 我试图将application.properties上的服务器端口更改为5000,但仍需要通过端口8080进行访问(5000告诉我“无法获得任何响应”) war的上传工作(通过tomcat管理器) 如果你需要一些细节,问我 谢谢你的帮助 注:我只是在我的日志上看到: f、 n.

我做了一些搜索,但在我的情况下什么都没有(或谁的解决方案)。我有一个使用SpringBoot和Tomcat9的JAVA API,当我在本地使用它时,所有这些都可以工作,但当我试图将API放在VPS上时,我无法访问它

见:

我试图将application.properties上的服务器端口更改为5000,但仍需要通过端口8080进行访问(5000告诉我“无法获得任何响应”) war的上传工作(通过tomcat管理器)

如果你需要一些细节,问我

谢谢你的帮助

注:我只是在我的日志上看到:

f、 n.a.s.JwtAuthenticationEntryPoint:响应未经授权的错误。消息-访问此资源需要完全身份验证

N.B2:我的SecurityConfig文件:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
    securedEnabled = true,
    jsr250Enabled = true,
    prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
    return new JwtAuthenticationFilter();
}

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

@Bean(BeanIds.AUTHENTICATION_MANAGER)
@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()
            .exceptionHandling()
            .authenticationEntryPoint(unauthorizedHandler)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/",
                    "/favicon.ico",
                    "/**/*.png",
                    "/**/*.gif",
                    "/**/*.svg",
                    "/**/*.jpg",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js")
            .permitAll()
            .antMatchers("/api/auth/**")
            .permitAll()
            .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
            .permitAll()
            .antMatchers(HttpMethod.GET, "/api/polls/**", "/api/users/**")
            .permitAll()
            .anyRequest()
            .authenticated();

    // Add our custom JWT security filter
    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

}}
和应用程序属性:

## Server Properties
server.port= 5000

## Spring DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.url= jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username= admin
spring.datasource.password= nox

## Hibernate Properties

# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update

## Hibernate Logging
logging.level.org.hibernate.SQL= DEBUG

## Jackson Properties
spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS= false
spring.jackson.time-zone= UTC
和应用程序文件:

@SpringBootApplication
@EntityScan(basePackageClasses = {
    ApiApplication.class,
    Jsr310JpaConverters.class
})
public class ApiApplication extends SpringBootServletInitializer {

@PostConstruct
void init() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(ApiApplication.class);
}

public static void main(String[] args) {
    SpringApplication.run(ApiApplication.class, args);
}
}
JwtAuthenticationFilter:

public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private JwtTokenProvider tokenProvider;

@Autowired
private CustomUserDetailsService customUserDetailsService;

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    try {
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
            Long userId = tokenProvider.getUserIdFromJWT(jwt);

            UserDetails userDetails = customUserDetailsService.loadUserById(userId);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    } catch (Exception ex) {
        logger.error("Could not set user authentication in security context", ex);
    }

    filterChain.doFilter(request, response);
}

private String getJwtFromRequest(HttpServletRequest request) {
    String bearerToken = request.getHeader("Authorization");
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
}

@是的。localhost:5000/api/auth/signup和163.x.xx.xxx:8080/api/auth/signup-only端口更改,我不知道为什么,但当我在163.x.xx.xxx上为server.port设置5000时忽略了