java - 401 Unauthorized 当我尝试远程访问 API 时
问题描述
我已经进行了一些搜索,但在我的情况下没有(或谁解决了)。我在 JAVA 中有一个使用 SpringBoot 和 Tomcat9 的 API,当我在本地使用它时,一切正常,但是当我试图将我的 API 放在我的 VPS 上时,我无法访问它。
见:https ://i.stack.imgur.com/khCPl.png
我尝试将我的 application.properties 上的服务器端口更改为 5000,但仍需要通过端口 8080 访问(5000 告诉我“无法得到任何响应”)战争的上传工作(通过 tomcat 管理器)。
如果你需要一些细节,问我。
谢谢你的帮助。
注意:我只是在我的日志中看到:
fnasJwtAuthenticationEntryPoint :响应未经授权的错误。消息 - 访问此资源需要完全身份验证
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);
}}
和 application.properties :
## 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;
}
}
解决方案
推荐阅读
- python - 如何防止win10toast冻结?
- iis - Converting Apache rewrite rules to IIS
- sql - PGSQL - 使用外键翻译查询结果
- spring - Spring Data Mongo 链接文档存储
- xcode - 为什么我的导航链接不起作用。我收到此错误:“'NavigationLink 的结果
- python - 带有可选参数的 SQLAlchemy 连接
- sql - 如何在 SQL 中加入/合并来自不同表的日期列
- node.js - D3 Sankey节点颜色排列
- sql - SQL执行顺序:它是否存在?
- javascript - 图表 JS:无法使用 Jquery 将饼图重新初始化为甜甜圈或甜甜圈到饼图