Spring Security 4不分配管理员角色

时间:2015-12-11 08:42:46

标签: java spring-mvc spring-security

我正在尝试使用spring mvc和spring security 4将管理员角色分配给我的Web应用程序中的用户。我手动将角色分配给数据库中的用户,然后我只是尝试访问我的网络应用程序中的网址,但是我收到403错误,如果我只是尝试以普通用户身份访问,那将会很好,但我正在使用管理员尝试访问它。我会展示一些我的代码,看看是否有人能看到我遗漏的东西。提前谢谢。

这是我的用户域对象

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@Table(name="users")
public class User {

private Long id;

@Size(min=4, max=30)
private String username;

private String password;

private String email;

private University university;

private Set<Course> courses = new TreeSet<>();

private Set<QuestionAnswerSet> questionAnswerSets = new TreeSet<>();

private Set<Post> posts = new TreeSet<>();

private Set<Comment> comments = new TreeSet<>();

private Set<Authorities> authorities = new HashSet<>();

public User () {}

public User(User user) {
    this.username = user.getUsername();
    this.password = user.getPassword();
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}
public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getPassword() {
    return password;
}

public CharSequence setPassword(String password) {
    return this.password = password;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

@ManyToOne
@NotNull
public University getUniversity() {
    return university;
}

public void setUniversity(University university) {
    this.university = university;
}

@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
public Set<Course> getCourses() {
    return courses;
}

public void setCourses(Set<Course> courses) {
    this.courses = courses;
}

@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="user")
public Set<QuestionAnswerSet> getQuestionAnswerSets() {
    return questionAnswerSets;
}

public void setQuestionAnswerSets(Set<QuestionAnswerSet> questionAnswerSets) {
    this.questionAnswerSets = questionAnswerSets;
}
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="user")
public Set<Post> getPosts() {
    return posts;
}

public void setPosts(Set<Post> posts) {
    this.posts = posts;
}
@JsonManagedReference
@OneToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL, mappedBy="user")
public Set<Comment> getComments() {
    return comments;
}
public void setComments(Set<Comment> comments) {
    this.comments = comments;
}

@OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
public Set<Authorities> getAuthorities() {
    return authorities;
}

public void setAuthorities(Set<Authorities> authorities) {
    this.authorities = authorities;
}

public static User createUser(String username, String email, String password) {
    User user = new User();

    user.username = username;
    user.email = email;
    user.password = new BCryptPasswordEncoder().encode(password);

    return user;
}

public User(Long id, String username, String password, String email, University university,
        Set<QuestionAnswerSet> questionAnswerSets, Set<Post> posts, Set<Comment> comments, Set<Authorities> authorities) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.email = email;
    this.university = university;
    this.questionAnswerSets = questionAnswerSets;
    this.posts = posts;
    this.comments = comments;
    this.authorities = authorities;
}

public User(UserDetails userDetails) {
    // TODO Auto-generated constructor stub
}
}

这是我当局的反对意见。在我的数据库中,我的id为“1”,权限为“ADMIN”,用户为“1”,与我输入数据库的第一个用户相对应。

@Entity
public class Authorities implements GrantedAuthority {

private static final long serialVersionUID = -2848940318555407665L;
private Long id;
private User user;
private String authority;

@Id
@GeneratedValue
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}
@ManyToOne
public User getUser() {
    return user;
}
public void setUser(User user) {
    this.user = user;
}
public String getAuthority() {
    return authority;
}
public void setAuthority(String authority) {
    this.authority = authority;
}
}

我的WebSecurityConfig

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private static PasswordEncoder encoder;

@Autowired
private UserDetailsService customUserDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
    .csrfTokenRepository(csrfTokenRepository());

    http
    .authorizeRequests()
        .antMatchers("/", "/home", "/register", "/courses", "/editCourse", "/sets", "/search", "/viewCourse/{courseId}", "/fonts/glyphicons-halflings-regular.ttf","/fonts/glyphicons-halflings-regular.woff", "/fonts/glyphicons-halflings-regular.woff2", "/viewCourse/post/{postId}", "/courseSearch", "/setSearch").permitAll()
        .antMatchers("/createCourse", "/addUniversities").hasRole("ADMIN")
        .anyRequest().authenticated();

    http
    .formLogin()
         .loginPage("/login")
         .usernameParameter("username").passwordParameter("password")
            .permitAll()
            .and()
         .logout()
            .permitAll()
            .logoutSuccessUrl("/loggedout")
            .and()
            .sessionManagement()
                .maximumSessions(1);


}

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

@Bean
public PasswordEncoder passwordEncoder() {
    if(encoder == null) {
        encoder = new BCryptPasswordEncoder();
    }

    return encoder;
}

private CsrfTokenRepository csrfTokenRepository() 
{ 
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
    repository.setSessionAttributeName("_csrf");
    return repository; 
}
}

自定义用户详细信息

public class CustomUserDetails extends User implements UserDetails{

private User user;

public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}

private static final long serialVersionUID = 2020921373107176828L;

public CustomUserDetails () {}

public CustomUserDetails (User user) {
    super(user);
}

@Override
public Set<Authorities> getAuthorities() {
    return super.getAuthorities();
}
@Override
public boolean isAccountNonExpired() {
    return true;
}
@Override
public boolean isAccountNonLocked() {
    return true;
}
@Override
public boolean isCredentialsNonExpired() {
    return true;
}
@Override
public boolean isEnabled() {
    return true;
}
}

我的UserDetailsS​​erviceImpl

@Service
@Qualifier("customUserDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

private UserRepository userRepo;

@Transactional
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    com.example.domain.User user = userRepo.findByUsername(username);

    CustomUserDetails customUserDetails = new CustomUserDetails(user);
    customUserDetails.setUser(user);

    return customUserDetails;
}

@Autowired
public void setUserRepo(UserRepository userRepo) {
    this.userRepo = userRepo;
}

}

1 个答案:

答案 0 :(得分:0)

如果您的数据库条目只是“ADMIN”,请使用hasAuthority()代替hasRole()

如果要使用hasRole,则应将数据库条目更改为“ROLE_ADMIN”