gpt4 book ai didi

java - spring security中的授权问题

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

我创建了自定义 UserDetailService 和安全配置。当我允许仅授权用户进入安全页面时 - 好的,但如果具有角色的用户 -HTTP 状态 403 – 禁止。我认为我没有正确处理角色。请帮忙

我的用户服务

public interface UserService extends UserDetailsService {

}
@Service
public class UserServiceImpl implements UserService{
@Autowired
private PasswordEncoder passwordEncoder;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = new User();

user.setUsername(username);
user.setPassword(passwordEncoder.encode("1"));

//There is the problem I think

List<SimpleGrantedAuthority> roleList = new ArrayList<>();

roleList.add(new SimpleGrantedAuthority("ADMIN"));
user.setRoleList(roleList);

//

user.setAccountNonExpired(true);
user.setAccountNonLocked(true);
user.setCredentialsNonExpired(true);
user.setEnabled(true);
return user;
}
}

安全配置

@Configuration
@EnableWebSecurity
@ComponentScan("something")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin*").authenticated() - it works
//.antMatchers("/admin*").hasRole("ADMIN") - it doesn't work
.anyRequest().permitAll()
.and()
.formLogin().permitAll()
.and()
.logout().permitAll()
.and().csrf().disable();
}

@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}

我的 User.class 以防万一

public class User implements Serializable, UserDetails {
//fields
}

最佳答案

为了将您的用户角色设置为“ADMIN”,您需要将权限设置为“ROLE_ADMIN”

roleList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

角色与以“ROLE_”为前缀的权限相同

关于java - spring security中的授权问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57462219/

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