gpt4 book ai didi

java - 如何在Spring Boot应用程序中添加方法级别身份验证?

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:16 25 4
gpt4 key购买 nike

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

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

}
}

我的 Controller 是

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。

最佳答案

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

它从未被映射。

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

关于java - 如何在Spring Boot应用程序中添加方法级别身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34995846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com