Spring Boot 403 запрещен с помощью запроса POST в Tomcat 9
Я новичок в весенней загрузке, и я создаю веб-приложение. Я пропускаю URL "/ auth / login" без аутентификации токена JWT.
Я создал контроллер, который обрабатывает запрос на вход и дает ответ.
Когда я вызываю свой веб-сервис с URL-адресом в моем локальном, используя URL http://localhost:9505/auth/login
с параметром тела
{
"username":"abcd@g.l",
"password" : "newPassword"
}
Он работает нормально и не проверяет токен, но когда я экспортирую его, создаю WAR-файл и развернул на сервере, он выдаст 403 Forbidden error.
Ниже приведен URL-адрес, который я использую для вызова API после развертывания на сервере Tomcat 9
http://localhost:9505/myapplicationame/auth/login
Подскажите пожалуйста, в чем будет проблема?
Ниже мой метод настройки безопасности.
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("SecurityConfig => configure : Configure in SecurityConfig");
logger.info("http Request Path : ");
logger.info("servletContext.getContextPath()) : " + servletContext.getContextPath());
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/auth/**")
.permitAll()
.antMatchers("/auth/login")
.permitAll()
.antMatchers("/permissions")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
Ниже мой класс фильтра
@Configuration
@CrossOrigin
@EnableWebSecurity
@EnableMBeanExport(registration=RegistrationPolicy.IGNORE_EXISTING)
@EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
@Order(SecurityProperties.IGNORED_ORDER)
public class JwtAuthenticationFilter extends OncePerRequestFilter {
@Autowired
JwtTokenProvider tokenProvider;
@Autowired
CustomUserDetailsService customUserDetailsService;
@Autowired
AdminPermissionRepository adminPermissionRepository;
@Autowired
PermissionMasterRepository permissionMasterRepository;
@Autowired
private ServletContext servletContext;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws IOException, ServletException {
if (StringUtils.hasText(jwt) && isValidToken) {
// Check user email and password
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
adminDetails, null, adminDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
logger.info("Before finish doFilterInternal");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
/**
* To get JWT token from the request
*
* @param httpServletRequest
* @return String
*/
private String getJwtFromRequest(HttpServletRequest httpServletRequest) {
logger.info("JwtAuthenticationFilter => getJwtFromRequest");
String bearerToken = httpServletRequest.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
logger.info("Have token");
return bearerToken.substring(7, bearerToken.length());
}
logger.info("Does not have token");
return null;
}
}
Ниже мой контроллер
@RestController
@Transactional(rollbackFor=Exception.class)
public class AuthController {
@PostMapping("/auth/login")
ResponseEntity login(@Valid @RequestBody LoginRequest request)
throws DisabledException, InternalAuthenticationServiceException, BadCredentialsException {
// My logic
return ResponseEntity.ok();
}
}
2 ответа
Проблема в CORS на моем сервере Tomcat.
Я прокомментировал код ниже, и это работает.
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:9505, http://localhost, www.mydomain.io, http://mydomain.io, mydomain.io</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Спасибо
Попробуйте добавить нижеупомянутые аннотации к вашему классу.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ServletContext servletContext;
@Override
protected void configure(HttpSecurity http) throws Exception {
logger.info("SecurityConfig => configure : Configure in SecurityConfig");
logger.info("http Request Path : ");
logger.info("servletContext.getContextPath()) : " + servletContext.getContextPath());
http
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/auth/**")
.permitAll()
.antMatchers("/auth/login")
.permitAll()
.antMatchers("/permissions")
.permitAll()
.anyRequest()
.authenticated();
// Add our custom JWT security filter
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}