wjrmffldrhrl / goldenblock

블록체인교육 프로젝트
1 stars 1 forks source link

check user role and enterprise login #47

Closed wjrmffldrhrl closed 4 years ago

wjrmffldrhrl commented 4 years ago

@xmxmqq @wz0405 유저 권한에 따른 접근 제한을 구현했습니다.

WebSecurityConfig.java


    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // For CORS error
        httpSecurity.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues());
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests()
                .antMatchers("/authenticate", "/register/*", "research/*").permitAll()
                .antMatchers("/only-student").hasRole("STUDENT").
                // all other requests need to be authenticated
                anyRequest().authenticated().and().

                // stateless session
                // exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

.antMatchers("/only-student").hasRole("STUDENT"). 이 부분에 의해서 /only-student url은 학생 유저만 접근 가능합니다.

UserDetails

public class StudentDetails extends User {
    private Student student;
    // 스프링 시큐리티가 다루는 유저 정보를 우리가 가지고 있는 도메인의 유저 정보와 연동
    public StudentDetails(Student student) {
        super(student.getEmail(), student.getPassword(), 
            List.of(new SimpleGrantedAuthority("ROLE_STUDENT")));
        this.student = student;
    }
}

hasRole() 메서드는 전달받는 변수("STUDENT")에 자동으로 "ROLE_"를 붙여서 검사하기 때문에 권한에 "ROLE_"를 추가하였습니다.

EnterpriseDetails도 동일합니다.