我一直在尝试使用Spring Security使用Basic Auth保护我的Spring Rest API。我希望对其进行配置,以便将用户存储在数据库中,并根据其角色可以访问不同的端点。
为简单起见,在下面的示例中,所有端点都需要“ ADMIN”角色。
我认为我已正确配置了所有内容(基于一些在线教程),但是似乎安全性无法处理比较我的UserAuthorities(角色)。
当我通过邮递员发送GET请求并使用用户名和密码进行授权时,找到了我的用户(我没有得到401),但是却得到了403,好像用户没有适当的角色。如果我更改(hasRole(Role.ADMIN.name()) to authenticated()
,则效果很好。您能否看一下我的代码并帮助我找出我所缺少的内容?
用户类别:
@Entity
@NoArgsConstructor
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String username;
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST)
private Set<UserAuthority> authorities = new HashSet<UserAuthority>();
public User(String username, String password) {
this.username = username;
this.password = password;
}
public void addAuthority(UserAuthority authority) {
authorities.add(authority);
}
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isEnabled() {
return true;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setAuthorities(Set<UserAuthority> authorities) {
this.authorities = authorities;
}
}
UserAuthority类:
@Entity
@Table(name = "authorities")
@NoArgsConstructor
@Getter
@Setter
public class UserAuthority implements GrantedAuthority {
@Id
@GeneratedValue
private Long id;
private String name;
public UserAuthority(String name) {
this.name = name;
}
public String getAuthority() {
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserAuthority authority = (UserAuthority) o;
return name != null ? name.equals(authority.name) : authority.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
}
安全配置类:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static String REALM = "MY_TEST_REALM";
//to be a bean later
private PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
@Autowired
UserDetailsService userDetailsService;
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/**").hasRole(Role.ADMIN.name())
.and().httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint())
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);//We don't need sessions to be created.
}
@Bean
public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint() {
return new CustomBasicAuthenticationEntryPoint();
}
/* To allow Pre-flight [OPTIONS] request from browser */
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
}
}
UserServiceImpl类的重要部分:
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserAuthorityRepository userAuthorityRepository;
private PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return userRepository.getUserByUserName(s);
}
}
我得到的响应是403:服务器理解了该请求,但拒绝对其进行授权。
userRepository.getUserByUserName(s)
向我返回具有正确权限的正确的User
对象。对不起,代码太多了,我只是不知道错误可能在哪里。
非常感谢您的帮助!
干杯
最佳答案
我解决了!原来,角色必须使用前缀“ ROLE_”保留,因此我将其添加到我的角色枚举中:
private static final String ROLE_PREFIX = "ROLE_";
public String nameWithPrefix() {
return ROLE_PREFIX + name();
}
现在可以了:)