Spring Tomcat 中的 POST 请求禁止引导 403 9
Spring Boot 403 forbidden with POST request in Tomcat 9
我是 spring 引导的新手,我正在创建一个 Web 应用程序。我在没有 JWT 令牌身份验证的情况下绕过“/auth/login”URL。
我创建了一个控制器来处理登录请求并给出响应。
当我在本地使用 URL 使用 URL 调用我的网络服务时
http://localhost:9505/auth/login
带有正文参数
{
"username":"abcd@g.l",
"password" : "newPassword"
}
它工作正常并且不检查令牌但是当我导出它并创建 WAR 文件并部署到服务器上时它给我 403 禁止错误。
下面是 URL,我在 tomcat 9 服务器
上部署后用来调用 API
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);
}
下面是我的过滤器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();
}
}
尝试在您的 class 中添加下面提到的注释。
@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);
}
}
问题出在我的 tomcat 服务器中的 CORS。
我在下面的代码中添加了注释,它有效。
<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>
谢谢
我是 spring 引导的新手,我正在创建一个 Web 应用程序。我在没有 JWT 令牌身份验证的情况下绕过“/auth/login”URL。
我创建了一个控制器来处理登录请求并给出响应。
当我在本地使用 URL 使用 URL 调用我的网络服务时
http://localhost:9505/auth/login
带有正文参数
{
"username":"abcd@g.l",
"password" : "newPassword"
}
它工作正常并且不检查令牌但是当我导出它并创建 WAR 文件并部署到服务器上时它给我 403 禁止错误。
下面是 URL,我在 tomcat 9 服务器
上部署后用来调用 APIhttp://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);
}
下面是我的过滤器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();
}
}
尝试在您的 class 中添加下面提到的注释。
@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);
}
}
问题出在我的 tomcat 服务器中的 CORS。
我在下面的代码中添加了注释,它有效。
<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>
谢谢