我正在使用Spring MVC架构开发Web应用程序,并通过Spring安全性对其进行保护。我将JPA存储库用于我的持久层。我遇到的问题是,当我尝试从应用程序中的特定页面(“添加实现”页面)发送POST请求时,出现以下错误消息:
There was an unexpected error (type=Forbidden, status=403). Forbidden
无论我的用户具有哪个角色(有两个角色:admin
和vendor
),都会发生这种情况。另外,当我使用configure(HttpSecurity http)
和antMatchers
在permitAll()
函数中明确允许有问题的Url时,甚至会发生这种情况。所以问题是,为什么我的POST请求未得到授权?
我是Spring Security的新手,可能在其中的任何配置中都犯了一个严重错误。我将附加与Spring安全性相关的所有代码以及相关的控制器。
下面是我的配置函数:网址/vendor/{id:[0-9]+}/addimpl
是给我带来麻烦的网址。我已经在这里明确允许它只是为了查看会发生什么,但是在发布到它时仍然出现403
错误(但是GET请求工作正常)。
@Configuration
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private AcvpUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/register", "/webjars/**", "/css/**",
"/images/**").permitAll()
.antMatchers("/vendor/{id:[0-9]+}/addimpl").permitAll()
.anyRequest().authenticated().and().formLogin()
.loginPage("/login").loginProcessingUrl("/login").successHandler(myAuthenticationSuccessHandler()).permitAll().and()
.logout().permitAll();
}
这是我的UserDetailsService
:
@Service
@Transactional
public class AcvpUserDetailsService implements UserDetailsService {
@Autowired
private AcvpUserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) {
AcvpUser user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
return new AcvpUserPrincipal(user);
}
}
还有UserDetails类...
@Transactional
public class AcvpUserPrincipal implements UserDetails {
/**
* this is necessary for posterity to know whether they can serialize this
* class safely
*/
private static final long serialVersionUID = 3771770649711489402L;
private AcvpUser user;
public AcvpUserPrincipal(AcvpUser user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.singletonList(new
SimpleGrantedAuthority(user.getRole()));
}
@Override
public String getPassword() {
return user.getPassword(); // this is now the encrypted password
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
这是我的AuthenticationSuccessHandler
课。在myAuthenticationSuccessHandler()
的configure函数中返回此实例。
public class AcvpAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
protected Log logger = LogFactory.getLog(this.getClass());
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Autowired
private AcvpUserRepository userRepository;
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
handle(request, response, authentication);
clearAuthenticationAttributes(request);
}
protected void handle(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException {
String targetUrl = determineTargetUrl(authentication);
if (response.isCommitted()) {
logger.debug(
"Response has already been committed. Unable to redirect to "
+ targetUrl);
return;
}
redirectStrategy.sendRedirect(request, response, targetUrl);
}
protected String determineTargetUrl(Authentication authentication) {
boolean isUser = false;
boolean isAdmin = false;
Collection<? extends GrantedAuthority> authorities
= authentication.getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals(AcvpRoles.VENDOR_ROLE)) {
isUser = true;
break;
} else if (grantedAuthority.getAuthority().equals(AcvpRoles.ADMIN_ROLE)) {
isAdmin = true;
break;
}
}
if (isUser) {
String username = authentication.getName();
AcvpUser user = userRepository.findByUsername(username);
return "/vendor/" + user.getVendor().getId();
} else if (isAdmin) {
return "/";
} else {
throw new IllegalStateException();
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
这是我pom文件中的Spring Security依赖项:
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<scope>runtime</scope>
</dependency>
这是控制器功能。我同时包含GET和POST,但请注意GET可以正常工作,而POST却给出了错误。我要指出的是,该程序不会进入POST功能。我设置了一个断点并尝试调试,但是在进入此功能之前它崩溃了。
@RequestMapping(value = "/vendor/{id:[0-9]+}/addimpl", method = RequestMethod.GET)
public String getAddImplementation(Model model, @PathVariable("id") Long id)
throws VendorNotFoundException {
Vendor vendor = vendorRepository.findById(id)
.orElseThrow(VendorNotFoundException::new);
model.addAttribute("vendor", vendor);
model.addAttribute("edit", false);
model.addAttribute("moduleTypes", ModuleType.values());
ImplementationAddForm backingObject = new ImplementationAddForm();
model.addAttribute("form", backingObject);
return "implementation-add-edit";
}
@RequestMapping(value = "/vendor/{id:[0-9]+}/addimpl", method = RequestMethod.POST)
public String saveImplementation(@PathVariable("id") Long id,
@ModelAttribute("implementation") @Valid ImplementationAddForm form,
BindingResult bindingResult, Model model, RedirectAttributes ra)
throws VendorNotFoundException {
Vendor vendor = vendorRepository.findById(id)
.orElseThrow(VendorNotFoundException::new);
if (bindingResult.hasErrors()) {
model.addAttribute("vendor", vendor);
model.addAttribute("edit", false);
model.addAttribute("moduleTypes", ModuleType.values());
model.addAttribute("form", form);
return "implementation-add-edit";
} else {
Implementation i = form.buildEntity();
i.setVendor(vendor);
implementationRepository.save(i);
return "redirect:/vendor/" + id;
}
}
最后,我包括在SecurityConfiguration类上设置“调试”的输出。这可能会有所帮助,但我无法从中得到任何东西。
Request received for POST '/vendor/33/addimpl':
org.apache.catalina.connector.RequestFacade@3b981cfd
servletPath:/vendor/33/addimpl
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
content-length: 402
cache-control: max-age=0
origin: http://localhost:8080
upgrade-insecure-requests: 1
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/vendor/33/addimpl
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=1121ADD15A2E23786464649647B62356
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
************************************************************
2018-12-21 09:49:32.570 INFO 4392 --- [nio-8080-exec-3] Spring Security
Debugger :
************************************************************
Request received for POST '/error':
org.apache.catalina.core.ApplicationHttpRequest@73210c23
servletPath:/error
pathInfo:null
headers:
host: localhost:8080
connection: keep-alive
content-length: 402
cache-control: max-age=0
origin: http://localhost:8080
upgrade-insecure-requests: 1
content-type: application/x-www-form-urlencoded
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
referer: http://localhost:8080/vendor/33/addimpl
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cookie: JSESSIONID=1121ADD15A2E23786464649647B62356
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
CsrfFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
在将POST请求发送到/vendor/33/addimpl
之后,如果进行验证,我希望将其重定向回到“供应商”页面,或再次重定向到“添加实现”页面(正是我发布的页面)。错误。但是这些都没有发生。相反,我被发送到默认错误页面。
答案 0 :(得分:0)
默认情况下启用CSRF(跨站请求伪造)。
您可能需要在AcvpUserDetailsService类中将其关闭
添加:
http.csrf().disable();
在此处了解有关CSRF的更多信息:https://www.baeldung.com/spring-security-csrf
答案 1 :(得分:0)
正如其他人所说,问题在于CSRF已启用,并且CSRF令牌未与POST请求一起发送。但是,我不想完全禁用CSRF,因为我希望该应用程序免受CSRF攻击。事实证明,在此应用程序中添加CSRF令牌非常容易。我使用thymeleaf作为模板工具,已经发布的任何链接中都找不到这种简单的解决方案,但是可以在这里找到:https://www.baeldung.com/csrf-thymeleaf-with-spring-security
我在登录表单中包含了以下代码:
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
根据上面的链接,这是所有必要的操作,但是对我而言,直到我将百里香th:
标记添加到所有表单动作中后,它才起作用。因此,我不必做<form action="<url>"
,而不必做<form th:action="@{<url>}"
。