>

스프링 부트 앱에서 스프링 보안을 사용하고 있습니다. 내 앱은 메모리 내 인증과 잘 작동합니다. 그러나 사용자가 데이터베이스에서로드되면 인증되지 않습니다. 403 액세스 거부 오류 코드를 반환합니다. UserDetailsService는 데이터베이스에서 사용자 정보를 가져올 수 있지만 어디에서 잘못되는지 알 수 없습니다. 저는 봄이 처음입니다.

여기에 보안과 관련된 완전한 코드가 있습니다

User.java

import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Entity
@Table(name = "user")
@Data
public class User {
    @Id
    @NotNull
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long userId;
    @Column(name = "USERNAME", unique = true)
    @NotNull
    private String username;
    @Column(name = "PASSWORD")
    @NotNull
    private String password;
    @Column(name = "DISPLAY_NAME")
    private String displayName;
    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "id")
    private Set<Role> userRoles;
    private String profilePicturePath;
}

Role.java

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "roles")
@Data
public class Role {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String role;
}

UserRepository.java

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.cloudsofts.cloudschool.people.users.pojos.User;
@Repository("userRepository")
public interface UserRepository extends JpaRepository<User, Long> {
    User findByUsername(String username);
}

RoleRepository.java

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.cloudsofts.cloudschool.people.users.pojos.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
}

UserService.java

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.cloudsofts.cloudschool.people.users.pojos.User;
import com.cloudsofts.cloudschool.people.users.repositories.UserRepository;
@Service
public class UserService {
    @Autowired
    UserRepository userRep;
    @Autowired
    private PasswordEncoder passwordEncoder;
    public List<User> getAllUsers() {
    List<User> users = userRep.findAll();
    return users;
    }
    public void addUser(User user) {
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    userRep.save(user);
    }
    public void updateUser(User user) {
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    userRep.save(user);
    }
    public void deleteUser(Long id) {
    userRep.delete(id);
    }
    public User getUser(Long id) {
    return userRep.findOne(id);
    }
}

RoleService.java

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cloudsofts.cloudschool.people.users.pojos.Role;
import com.cloudsofts.cloudschool.people.users.repositories.RoleRepository;
@Service
public class RoleService {
    @Autowired
    RoleRepository userRoleRep;
    public void addUserRole(Role role) {
    userRoleRep.save(role);
    }
    public void updateUserRole(Role role) {
    userRoleRep.save(role);
    }
    public void deleteUserRole(Long id) {
    userRoleRep.delete(id);
    }
    public Role getUserRole(Long id) {
    return userRoleRep.findOne(id);
    }
    public List<Role> getAllUserRoles() {
    return userRoleRep.findAll();
    }
}

CustomUserDetails.java

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import lombok.Data;
@Data
public class CustomUserDetails implements UserDetails {
    private static final long serialVersionUID = 1L;
    private User user;
    public CustomUserDetails(final User user) {
    this.user = user;
    }
    public CustomUserDetails() {
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
    final Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
    Set<Role> roles = null;
    if (user != null) {
        roles = user.getUserRoles();
    }
    if (roles != null) {
        for (Role role : roles) {
        authorities.add(new SimpleGrantedAuthority(role.getRole()));
        }
    }
    return authorities;
    }
    @Override
    public String getPassword() {
    return user.getPassword();
    }
    @Override
    public String getUsername() {
    return user.getUsername();
    }
    @Override
    public boolean isAccountNonExpired() {
    return true;
    }
    @Override
    public boolean isAccountNonLocked() {
    return true;
    }
    @Override
    public boolean isCredentialsNonExpired() {
    return true;
    }
    @Override
    public boolean isEnabled() {
    return true;
    }
}

CustomUserDetailsService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.cloudsofts.cloudschool.people.users.pojos.CustomUserDetails;
import com.cloudsofts.cloudschool.people.users.pojos.Role;
import com.cloudsofts.cloudschool.people.users.pojos.User;
import com.cloudsofts.cloudschool.people.users.repositories.UserRepository;
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserRepository userRepository;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = userRepository.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException(username);
    } else {
        System.out.println("______________________________________________________________");
        System.out.println("username: " + user.getUsername());
        System.out.println("password: " + user.getPassword());
        System.out.println("Roles: ");
        for (Role role : user.getUserRoles()) {
        System.out.println(role.getRole());
        }
        System.out.println("______________________________________________________________");
        return new CustomUserDetails(user);
    }
    }
}

SecurityConfig.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
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.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.cloudsofts.cloudschool.security.CustomUserDetailsService;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Qualifier("userDetailsService")
    @Autowired
    CustomUserDetailsService userDetailsService;
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
    try {
        auth.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder());
        System.out.println("_________________________________________________");
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println("_________________________________________________");
        System.out.println("You have logged in as " + username);
        System.out.println("_________________________________________________");
    } catch (Exception e) {
        System.out.println("_________________________________________________");
        System.out.println(e.getMessage());
        System.out.println("_________________________________________________");
    }
    }
    @Bean(name = "passwordEncoder")
    public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
    }
    /*
     * @Autowired public void configureGlobal(AuthenticationManagerBuilder auth)
     * throws Exception {
     * auth.inMemoryAuthentication().withUser("student").password("student").roles(
     * "student").and().withUser("admin") .password("admin").roles("admin"); }
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    // http.authorizeRequests().anyRequest().permitAll();
    // http.authorizeRequests().antMatchers("/api/**").permitAll();
    http.authorizeRequests().antMatchers("/student/**").hasAnyRole("student", "admin");
    http.authorizeRequests().antMatchers("/api/admin/**").hasRole("admin");
    http.authorizeRequests().antMatchers("/library/**").hasAnyRole("librarian", "admin");
    http.httpBasic();
    // http.formLogin().and().logout().logoutSuccessUrl("/login?logout").permitAll();
    }
}

스크린 샷

우체국 스크린 샷

브라우저 스크린 샷

DB 사용자

DB의 역할

사용자 역할 매핑

자격 증명을 제공 한 후 콘솔 출력


  • 답변 # 1

    BCryptPasswordEncoder를 사용하여 비밀번호를 암호화 및 복호화하는 것 같습니다. 그러나 '사용자'테이블 스크린 샷은 비밀번호를 일반 텍스트로 표시합니다. 사용자를 저장하거나 업데이트하는 장소를 확인할 수 있습니까? 실제로 비밀번호를 인코딩하고 있으며 비밀번호 인코더 Bean은 'BCryptPasswordEncoder'유형입니다.

  • 답변 # 2

    문제가 해결되었습니다.

    역할의 접두사로ROLE _을 추가해야했습니다.

    이제 모든 것이 잘 작동합니다

  • 이전 excel - A 열에 텍스트가있는 경우 행 삽입
  • 다음 c# - 제한이있는 동시 사전