[英]How to add method level authentication in Spring Boot Application?
I am working on spring boot application, My requirement is to add Method level security to access data. 我正在开发Spring Boot应用程序,我的要求是添加方法级别的安全性以访问数据。 I am facing problem when I add @PreAuthorize in my controller it redirect to error page when I access any method of this controller.
我在控制器中添加@PreAuthorize时遇到问题,当我访问该控制器的任何方法时,它会重定向到错误页面。
My WebSecurityConfigurerAdapter is 我的WebSecurityConfigurerAdapter是
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${app.secret}")
private String applicationSecret;
@Autowired
private UserDetailsService userDetailsService;
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "contactus", "aboutus", "gallery", "signup").permitAll()
.antMatchers("/user/register").permitAll()
.antMatchers("/user/autologin")
.access("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPER') or hasRole('ROLE_USER')")
.antMatchers("/user/delete").access("hasRole('ROLE_ADMIN')").antMatchers("/user/**")
.access("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPER') or hasRole('ROLE_USER')")
.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')").antMatchers("/super/**")
.access("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPER')");
http.formLogin().failureUrl("/login?error").defaultSuccessUrl("/user/home").loginPage("/login").permitAll()
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.permitAll().and().exceptionHandling().accessDeniedPage("/403").and().csrf().and().rememberMe()
.key(applicationSecret).tokenValiditySeconds(31536000);
}
}
and my controller is 而我的控制器是
public interface OrganizationApi {
@PreAuthorize("hasAuthority('ROLE_USER')")
@RequestMapping(value="/user/organization/edit/{id}", method = RequestMethod.GET)
String update(@PathVariable Long id, Model model) throws Exception;
@PreAuthorize("@userServiceImpl.canAccessUser(principal, #id)")
@RequestMapping(value="/user/myorganizations", method = RequestMethod.GET)
String getAllOrganizationByUserId(Model model);
}
@Controller
public class OrganizationApiImpl extends RequestMappings implements OrganizationApi {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
OrgService orgService;
@Autowired
UserService userService;
@Override
public String getAllOrganizationByUserId(Model model) {
model.addAttribute("organizations",
orgService.listAllOrganizationByUserId(userService.getLoggedInUser().getId()));
return "organizations";
}
@Override
public String update(@PathVariable Long id, Model model) throws Exception {
if (userService.getLoggedInUser().getId() != orgService.getOrgById(id).getUserId()) {
model.addAttribute("error","You are not authorised to edit this recored.");
return "error";
}
model.addAttribute("organization", orgService.getOrgById(id));
return "addorganization";
}
}
In this when I comment @PreAuthorize my application works fine but when @PreAuthorize enabled application does not work and redirected to error page. 在这种情况下,当我评论@PreAuthorize时,我的应用程序可以正常工作,但是当启用@PreAuthorize的应用程序无法正常工作并重定向到错误页面时。
Is there anything that i missed in configuration? 我在配置中有什么想念的吗?
I got error on browser console 404 /user/myorganizations not found. 我在浏览器控制台404 / user / myorganizations上找不到错误。
Your interface is missing the @Controller
annotation, which is why you're getting a 404 error when trying to access the endpoint. 您的界面缺少
@Controller
批注,这就是为什么在尝试访问端点时收到404错误的原因。
It never got mapped. 它从未被映射过。
Spring will actually output all mappings on startup, so you should check the logs first, when you encounter an unexpected 404 error like that. Spring实际上会在启动时输出所有映射,因此,当您遇到类似这样的意外404错误时,应首先检查日志。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.