我已经使用了Spring Boot,安全认证,JPA和REST
这给我403错误,这是基于角色的错误。我尝试了2天无法解决,请帮忙。
我在这里共享代码。
这是我的安全性配置类,其角色针对所有用户/ hello,针对/ admin / all和/ admin / add。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encodePsw());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/api/secure/admin/**").hasRole("ADMIN").antMatchers("/api/secure/**")
.hasAnyRole("USER", "ADMIN").anyRequest().authenticated().and().formLogin().permitAll();
}
@Bean
public BCryptPasswordEncoder encodePsw() {
return new BCryptPasswordEncoder();
}
}
这是我的Controller类,具有3个方法,对于所有用户来说都是基于/ hello的3个角色,对于管理员用户来说是/ admin / all和/ admin / add的3个角色。
@RestController
@RequestMapping("/api/secure")
public class AdminController {
@Autowired
private UserRepository userRepo;
@Autowired
private BCryptPasswordEncoder passEncp;
@RequestMapping(value = "/hello")
public String hello() {
return "Hello..";
}
//@PreAuthorize("hasAnyRole('ADMIN')")
@RequestMapping(value = "/admin/add", method = RequestMethod.POST)
public String addUserByAdmin(@RequestBody User user) {
user.setPassword(passEncp.encode(user.getPassword()));
userRepo.save(user);
return "Add User Successfully";
}
//@PreAuthorize("hasAnyRole('ADMIN')")
@GetMapping("/admin/all")
public String securedHello() {
return "Secured Hello";
}
}
这是角色bean
@Entity
@Data
public class Role {
@Id
@GeneratedValue
private int roleId;
private String role;
}
此用户Bean
@Entity
@Setter
@Getter
public class User {
@Id
private int userId;
private String username;
private String password;
private String email;
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name="user_role", joinColumns = @JoinColumn(name="user_id"), inverseJoinColumns = @JoinColumn(name="role_id"))
private Set<Role> roles;
}
UserRepository界面
public interface UserRepository extends JpaRepository<User, Integer> {
User findByUsername(String username);
}
CustomUserDetails类 我认为这是问题所在。我有ROLE_USER之类的保存角色,ROLE_ADMIN也尝试过不带ROLE _
@Getter
@Setter
public class CustomUserDetails implements UserDetails {
private User user;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return user.getRoles().stream().map(role -> new SimpleGrantedAuthority(""+role))
.collect(Collectors.toList());
}
@Override
public String getPassword() {
// TODO Auto -generated method stub
return user.getPassword();
}
@Override
public String getUsername() {
// TODO Auto-generated method stub
return user.getUsername();
}
服务类CustomUserDetailsService
@Service
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
CustomUserDetails userDetails = null;
if(user!=null) {
userDetails = new CustomUserDetails();
userDetails.setUser(user);
}else {
throw new UsernameNotFoundException("User not found with name "+username);
}
return userDetails;
}
}
我还有另一个正在运行的具有不同URL映射的Controller类
请帮助
答案 0 :(得分:0)
WebSecurityConfigurerAdapter包含一个重载的配置消息,该消息以WebSecurity作为参数,接受要忽略的请求上的蚂蚁匹配器。
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/hello");
}
对于所有用户,您都可以忽略基于/ hello的网址。
答案 1 :(得分:0)
实际:
return user.getRoles().stream().map(role->new SimpleGrantedAuthority("ROLE_"+role)).collect(Collectors.toList());
预期:
return user.getRoles().stream().map(role->new SimpleGrantedAuthority("ROLE_"+role.getRole_name())).collect(Collectors.toList());