安全配置不能让我在某些页面上使用antmatchers()。以下是一个配置代码,我试图在其中不要在用户访问中签名"/","/条目","/igeup"。有了"/注册",没有问题,让我访问该页面,但是如果我试图访问"/"或"//renties",它会一直将我重定向到登录页面。我尝试在单独的抗匹配者()和切换订单中写下每个URI,但到目前为止尚无运气。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
DetailService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(User.PASSWORD_ENCODER);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/entries","/signup").permitAll()
.antMatchers("/adminpanel/**")
.access("hasRole('ROLE_ADMIN')")
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(loginSuccessHandler())
.failureHandler(loginFailureHandler())
.and()
.logout()
.permitAll()
.logoutSuccessUrl("/clearConnection")
.and()
.csrf();
http.headers().frameOptions().disable();
}
public AuthenticationSuccessHandler loginSuccessHandler() {
return (request, response, authentication) -> response.sendRedirect("/");
}
public AuthenticationFailureHandler loginFailureHandler() {
return (request, response, exception) -> {
response.sendRedirect("/login");
};
}
@Bean
public EvaluationContextExtension securityExtension() {
return new EvaluationContextExtensionSupport() {
@Override
public String getExtensionId() {
return "security";
}
@Override
public Object getRootObject() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return new SecurityExpressionRoot(authentication) {
};
}
};
}
}
显然我有一个带有注释@controllerAdvice(basepackages =" myproject.web.controller")的UserHandler类。这意味着它适用于提供的所有类别的包装。我的Adduser()试图将用户添加为属性,如果没有用户,则在同一类中定义的一个例外,这会导致重定向。因此,我在为@ControllerAdvice提供的包装外创建了单独的访客controller,并处理其中的所有逻辑。那解决了我的问题。如果有良好的实践,都会感谢您对我的方法的任何见解。
@ControllerAdvice(basePackages = "myproject.web.controller")
public class UserHandler {
@Autowired
private UserService users;
@ExceptionHandler(AccessDeniedException.class)
public String redirectNonUser(RedirectAttributes attributes) {
attributes.addAttribute("errorMessage", "Please login before accessing website");
return "redirect:/login";
}
@ExceptionHandler(UsernameNotFoundException.class)
public String redirectNotFound(RedirectAttributes attributes) {
attributes.addAttribute("errorMessage", "Username not found");
return "redirect:/login";
}
@ModelAttribute("currentUser")
public User addUser() {
if(SecurityContextHolder.getContext().getAuthentication() != null) {
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = users.findByUsername(username);
if(user != null) {
return user;
} else {
throw new UsernameNotFoundException("Username not found");
}
} else {
throw new AccessDeniedException("Not logged in");
}
}
}