gpt4 book ai didi

java - Spring security - 限制对我的更新个人资料页面的访问

转载 作者:行者123 更新时间:2023-12-01 11:24:40 24 4
gpt4 key购买 nike

我在我的应用程序中使用 spring security 并遇到了问题。我的应用程序有一个更新配置文件页面。我已添加 preAuthorized() 和请求映射为

@PreAuthorize("isAuthenticated()")
@RequestMapping (value="/user/{uid}/profile/update", method = GET)
public String updateProfileView(@ModelAttribute("form") UserProfileForm form, @PathVariable ("uid") Integer userId, Model model){

它工作正常,未经身份验证的用户无法访问此页面。

但问题是每个经过身份验证的用户都可以访问此页面

例如:用户 A 登录应用程序,他/她将能够更新每个人的个人资料。

我的 CustomUserDetailService 类是

@Service
@Transactional
public class CustomUserDetailsService implements UserDetailsService {

@Resource
UserService userService;

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
com.analyst.future.domain.User user = userService.getUser(email);

SimpleGrantedAuthority auth = new SimpleGrantedAuthority("ROLE_USER");

Collection<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
authorities.add(auth);

User userDeatails = new User(user.getEmail(), user.getPassword(), authorities);
return userDeatails;

}

}

我认为我不能用角色来限制它,因为每个经过身份验证的用户都将拥有相同的角色。

有什么方法可以限制经过身份验证的用户仅访问 self 更新个人资料页面。

最佳答案

我不是 Spring Security 专家,但请尝试阅读有关使用基于表达式的访问的信息 - Link here

有一条很小的线符合你想要的 -

For example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write

@PreAuthorize("#contact.name == authentication.name")
public void doSomething(Contact contact);

我认为在你的情况下会是这样的

@PreAuthorize("email == authentication.email")

虽然这是方法级别,所以也许不是您正在寻找的?好消息是,有一种方法可以使用登录用户并将其与请求用户进行匹配。 :)

关于java - Spring security - 限制对我的更新个人资料页面的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926210/

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