gpt4 book ai didi

java - Spring 安全: issues 403 after authorization with single granted

转载 作者:行者123 更新时间:2023-12-01 19:58:01 26 4
gpt4 key购买 nike

使用过 Spring Boot 2 + Spring Security Starter。

授权用户,但由于某种原因给出错误 403。

我尝试以不同的方式进行配置,但不起作用。

授权成功后(loadUserByUsername方法工作正常),它在所有带有/admin 前缀的页面上显示 403,在授权之前,切换到任何带有此前缀的页面都会导致重定向到/login

@Controller
public class AdminController {
@RequestMapping(value = "/admin", method = {GET, POST})
public String adminMainPage() {
return "redirect:/admin/article";
}
}

@Controller
@RequestMapping("/admin/article")
public class ArticleController {
@RequestMapping(value = "", method = {GET, POST})
public ModelAndView indexAdminPage(...){
...
}
}

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements UserDetailsService {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.userDetailsService(this)
.authorizeRequests()
.antMatchers("/", "/login",
"/login*", "/assets/**", "/lib/**", "/page.scripts/*").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.usernameParameter("login")
.passwordParameter("password")
.successForwardUrl("/admin")
.permitAll()
.and()
.logout()
.deleteCookies("JSESSIONID")
.permitAll();
}

private Collection<? extends GrantedAuthority> adminGrantedAuthoritySet = new HashSet<>() {{
add(new SimpleGrantedAuthority("ADMIN"));
}};

private final UserRepository userRepository;

public WebSecurityConfig(UserRepository userRepository ) {
this.userRepository = userRepository;
}

@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
Optional<UserEntity> optionalUser = userRepository.findByLogin(login);
if (optionalUser.isEmpty()) {
throw new UsernameNotFoundException("User by login '" + login + "' not found");
} else {
UserEntity userEntity = optionalUser.get();
return new User(login, userEntity.getPassword(), adminGrantedAuthoritySet);
}
}
}

最佳答案

在 Spring Security 中,角色权限之间是有区别的。
角色是一个权限,前缀为“ROLE_”。在此示例中,权限“ROLE_ADMIN”与角色“ADMIN”相同。

您将管理员authorities设置为new SimpleGrantedAuthority("ADMIN")列表,但您限制对.hasAnyRole("ADMIN"的访问“)

您需要更改其中一项配置。
如果您使用 .hasAnyRole("ADMIN"),则应更改管理 authorities 列表以使用 new SimpleGrantedAuthority("ROLE_ADMIN")
否则,如果您希望列表为 new SimpleGrantedAuthority("ADMIN"),那么您应该使用 .hasAnyAuthority("ADMIN")

关于java - Spring 安全: issues 403 after authorization with single granted,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023358/

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