스프링 부트 1.4.1 응용 프로그램 (일부 REST 웹 서비스를 구현 함)에서 작업 중이며 스프링 보안을이 프로젝트에 구현하려고 할 때 어려움을 겪고 있습니다.Spring Security가이 Spring Boot REST API 프로젝트에서 작동하지 않는 이유는 무엇입니까? 항상 "403 Forbidden"오류가 발생했습니다
나는 다음과 같은 상황이 :
1) 나는 봄 보안 된 UserDetails 인터페이스를 구현하는 CustomUserDetails 있습니다
import com.betrivius.domain.User;
import com.betrivius.domain.UserRole;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class CustomUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
public CustomUserDetails(User user){
super(user);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
for(UserRole role : this.getUserRoles()){
GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(role.getName());
authorities.add(grantedAuthority);
}
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
@Override
public String getUsername() {
return super.getUsername();
}
}
2) 그런 다음 나는 CustomUserDetailsService는 구현이를 봄 보안 UserDetailsService 인터페이스 :
,import com.betrivius.dao.UserDAO;
import com.betrivius.domain.User;
import com.betrivius.security.bean.CustomUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService{
@Autowired
private UserDAO userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("No user present with username: "+username);
}else{
return new CustomUserDetails(user);
}
}
}
3) Finnally 나는 WebSecurityConfigWebSecurityConfigurerAdapter을 확장라는 이름의 봄 보안 confinguration 클래스가 : 구성 클래스의 이전 코드에서 볼 수 있듯이
import com.betrivius.security.service.CustomUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@ComponentScan(basePackageClasses = CustomUserDetailsService.class)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/Accomodation/**").access("hasRole('ROLE_USER')")
.anyRequest().permitAll()
.and()
.csrf().disable();
/*.and()
.formLogin().loginPage("/login")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/login?logout")
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.csrf();*/
}
@Bean(name = "passwordEncoder")
public PasswordEncoder passwordencoder() {
return new BCryptPasswordEncoder();
}
}
내가 지정한 해당 ROLE_USER이 (가) 설정된의 사용자는 /Accomodation/ 경로 아래의 모든 리소스에 액세스 할 수 있습니다. 수행자 :
,210.antMatchers("/Accomodation/**").access("hasRole('ROLE_USER')")
4)이 이전 CustomUserDetailsService 클래스로 사용되는 사용자 정보를 얻으 UserDAO입니다 :
@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface UserDAO extends JpaRepository<User, Long> {
User findByUsername(String username);
@Query("SELECT r FROM User u JOIN u.userRoles r where u.username = :username")
List<UserRole> findRoleByUserName(String username);
}
사용자 이름과 암호가 DB에 토드되고
은 다음과 같습니다사용자 이름 : ErSabba
비밀 번호 : pswd
사용자 테이블 User_Roles, ErSabba 사용자의 역할이 많은 관계로 다수가 (같은 역할 USER 설정 시도) ROLE_USER이다.
당신이 볼 수 있듯이 :
http://localhost:8080/Accomodation/7
이 방법으로 이전 자격 증명을 전달 :
그래서, 우편 배달부 크롬 플러그인에서 나는 URL 향해 GET 요청을 수행 문제는 올바른 사용자 이름과 암호를 기본 인증 양식에 넣으면 그게 입니다. 403 오류 액세스가 거부되었습니다..
나는 그것이 인증을 수행했지만 권한이 없다는 것을 의미한다고 생각합니다.
이상한 점은 나 또한 나쁜 신임장을 넣으려고했는데 항상 대신에 같은 것을 얻는 것입니다. 잘못된 신임장 오류.
또한합니다 (사용자 정보를 검색하는)을 CustomUserDetailsService 클래스로 loadUserByUsername() 방법이 줄에 중단 점을 뒀다.
User user = userDao.findByUsername(username);
는
는 어떤 문제가 될 수 ... 봄 보안 구성하지 잘 작동되는 것 같아요 그래서이 줄에 멈추지 않는다 디버그 모드에서 실행? 내가 뭘 놓치고 있니? 어떻게 해결할 수 있습니까?
여기서 인증 토큰을 생성하고 있습니까? 인증 공급자가 누락 된 것 같습니다. –
@dur 예 중단 점을 여기에두면 중지됨 – AndreaNobili
@dur 정확히 구성해야하는 내용에 대한 추가 정보를 제공해 주시겠습니까? :-) – AndreaNobili