【问题标题】:How to add method level authentication in Spring Boot Application?如何在 Spring Boot Application 中添加方法级别的身份验证?
【发布时间】:2016-05-01 22:53:42
【问题描述】:

我正在开发 Spring Boot 应用程序,我的要求是添加方法级别的安全性来访问数据。当我在控制器中添加 @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 not found.

【问题讨论】:

  • 错误信息是什么?如果您毕竟没有必要的角色,重定向到错误页面可能是正确的..
  • 堆栈跟踪中没有错误消息,也没有进入调试点。只需重定向到我的错误页面。
  • @mhlz 我在浏览器控制台上遇到错误 404 /user/myorganizations not found.

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


【解决方案1】:

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

它从未被映射。

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

【讨论】:

  • OrganizationApiImpl 由@Controller 注释。我应该将 OrganizationApi 注释为@Controller。在此,当我评论 @PreAuthorize("hasAuthority('ROLE_USER')") 行时,它工作正常,但在删除评论后,相同的应用程序不起作用,并且堆栈中没有错误,仅在控制台我得到了这个 404 错误。
猜你喜欢
  • 2018-05-27
  • 1970-01-01
  • 2012-07-05
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2018-02-27
  • 2017-04-12
  • 1970-01-01
相关资源
最近更新 更多