我正在学习春季安全性,并且已经在Youtube上学习了很少的教程,我已经完成了作者/老师所教的任务,但是不幸的是,登录后尝试访问/ user和/ admin的URL时,我无法登录我从具有USER_USER和USER_ADMIN角色的数据库中收到授权的对象,但是当我请求这些URL时,我抛出了禁止访问的异常,任何人都可以指导为什么发生这种情况?
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private MyUserDetailsService userDetailsService;
/*Authentication method*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//auth.inMemoryAuthentication().withUser("admin").password("admin").roles("Admin").and().withUser("user").password("user").roles("User");
auth.userDetailsService(userDetailsService);
}
// Authorization - Should be from most secure to least one
@Override
protected void configure(HttpSecurity http) throws Exception {
// To allow access to any url without permission is by using permitAll() method
System.out.println("Accessign URL : ");
http.authorizeRequests().
antMatchers("/admin").hasRole("USER_ADMIN").
antMatchers("/user").hasAnyRole("USER_USER", "USER_ADMIN").
antMatchers("/", "static/css", "static/js").
permitAll().
and().
formLogin();
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
MyUserDetails类别:
package com.springsecurity.demo.models;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class MyUserDetails implements UserDetails {
private static final long serialVersionUID = -3042145577630945747L;
private String userName;
private String password;
private List<GrantedAuthority> authorityList;
public MyUserDetails() {
}
public MyUserDetails(User user) {
this.userName = user.getUserName();
this.password = user.getPassword();
this.authorityList = Arrays.stream(user.getUserRole().trim().split(",")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
System.out.println((this.authorityList.size() > 0 ? this.authorityList.get(0) : "Empty"));
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorityList;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return userName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
MyUserDetailsService类:
@Service
public class MyUserDetailsService implements UserDetailsService {
private UserRepository userRepository;
public MyUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
Optional<User> user = userRepository.findByUserName(userName);
user.orElseThrow(() -> new UsernameNotFoundException("User not found with name : " + userName));
return user.map(MyUserDetails::new).get();
}
}
UserRepository类:
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
Optional<User> findByUserName(String userName);
}
控制器类:
@RestController
public class GreetingController {
@RequestMapping(value = "/")
public String greet() {
return "Hello World!";
}
@RequestMapping(value = "/user")
public String greetUser() {
return ("<h1>Hello User!</h2");
}
@RequestMapping(value = "/admin")
public String greetAdmin() {
return ("<h1>Hello Admin!</h2");
}
}
谢谢
protected void configure(HttpSecurity http) throws Exception {
// To allow access to any url without permission is by using permitAll() method
System.out.println("Accessign URL : ");
http.authorizeRequests().
antMatchers("/admin", "/api/v1/users").hasRole("ADMIN").
antMatchers("/api/v1/students", "/api/v1/courses").hasAnyRole("USER", "ADMIN").
antMatchers("/", "static/css", "static/js").
permitAll().
and().
formLogin();
}