如何在Spring Boot Application中添加方法级别身份验证?

时间:2016-01-25 15:10:40

标签: java spring spring-mvc spring-security spring-boot

我正在开发Spring启动应用程序,我的要求是添加方法级安全性来访问数据。我在控制器中添加 @PreAuthorize 时遇到问题,当我访问此控制器的任何方法时,它会重定向到错误页面。

我的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);

}
}

我的控制器是

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";
}
}

当我评论@PreAuthorize时,我的应用程序工作正常,但启用了@PreAuthorize时,应用程序无效并重定向到错误页面。

我在配置中遗漏了什么吗?

我在浏览器控制台404 / user / myorganizations上找不到错误。

1 个答案:

答案 0 :(得分:0)

您的界面缺少@Controller注释,这就是您在尝试访问端点时遇到404错误的原因。

它从未被映射过。

Spring实际上会在启动时输出所有映射,所以当遇到意外的404错误时,你应该先检查日志。