0
我想分配管理角色給我的網絡應用程序中的用戶使用春天mvc和春季安全4.我手動分配給用戶在數據庫中的角色,然後我只是試圖訪問我的網絡應用程序中的網址,但是我得到了403錯誤,如果我只是想以普通用戶的身份訪問,但是我正在使用管理員嘗試訪問它,這會很好。我會展示一些我的代碼,看看有沒有人能看到我要離開的東西。提前致謝。春季安全4不分配管理員角色
這裏是我的用戶域對象
@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;
}
}
而且我UserDetailsServiceImpl
@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;
}
}