我一直在尝试使用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
对象。
我很抱歉有这么多代码,我只是不知道错误可能在哪里。 非常感谢您的帮助! 干杯
答案 0 :(得分:0)
我解决了!事实证明角色必须使用前缀&#34; ROLE _&#34;来保留,所以我将其添加到我的角色枚举中:
private static final String ROLE_PREFIX = "ROLE_";
public String nameWithPrefix() {
return ROLE_PREFIX + name();
}
现在有效:)