Today
-
Yesterday
-
Total
-
  • Spring Security UserDetail 커스터마이징
    카테고리 없음 2020. 11. 9. 10:27
    @Service
    public class UserService implements UserDetailsService {
    
        @Value("${onm.internal.iaaa}")
        private String iaaaServer;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            String iaaaUserUrl = iaaaServer + "/v2/user/";
            RestTemplate restTemplate = new RestTemplate();
    
            UserDto iaaaUser = restTemplate.getForObject(iaaaUserUrl + username, UserDto.class);
            System.out.println(iaaaUser);
            if (iaaaUser.getUserId() == null) {
                throw new UsernameNotFoundException(username);
            } else {
                return iaaaUser;
            }
        }
    }
    @Getter
    @Setter
    @NoArgsConstructor
    public class UserDto implements UserDetails {
    
        private String userId;
        private String userNm;
        private String userPw;
        private String usageTp;
        private String propTemplate;
    
        private String enabled;
        private String accountExpired;
        private String credentialsExpired;
        private String accountLocked;
    
        private Date regDt;
        private String regId;
        private Date modDt;
        private String modId;
    
        private List<UserPropDto> userPropList;
        private List<UserGrantDto> userGrantList;
    
        private List<GroupDto> grantGroups;
        private List<RoleDto> grantRoles;
        private List<ApiDto> grantApis;
        private List<MenuDto> grantMenus;
    
    
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            ArrayList<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
            auth.add(new SimpleGrantedAuthority("MEMBER"));
            return auth;
        }
    
        @Override
        public String getPassword() {
            return this.userPw;
        }
    
        @Override
        public String getUsername() {
            return this.userId;
        }
    
        @Override
        public boolean isAccountNonExpired() {
            return true;
    //        return !this.accountExpired.equals("Y");
        }
    
        @Override
        public boolean isAccountNonLocked() {
            return true;
    //        return !this.accountLocked.equals("Y");
        }
    
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
    //        return !this.credentialsExpired.equals("Y");
        }
    
        @Override
        public boolean isEnabled() {
            return true;
    //        return !this.enabled.equals("Y");
        }
    
    
        @Override
        public String toString() {
            ObjectMapper objectMapper = new ObjectMapper();
            String toStrValue = "";
            try {
                toStrValue = objectMapper.writeValueAsString(this);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return toStrValue;
        }
    }
    /**
     * WebSecurityConfig
     */
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Value("${spring.profiles.active}")
        private String activeProfile;
    
        @Autowired
        private UserService userService;
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            // the size can be between 4 to 31
    //        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            String defaultUrl = activeProfile.equals("local")?"/dashboard":"/portal/dashboard";
    //        System.out.println("configure activeProfile:" + activeProfile);
            http.csrf().disable()
                    .authorizeRequests()
                    .antMatchers("/actuator/**").permitAll()
                    .antMatchers("/error/**").permitAll()
                    .antMatchers("/auth/**").permitAll()
                    .antMatchers("/menu/**").permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                        .formLogin()
                        .loginPage("/auth/loginPage")
                        .loginProcessingUrl("/auth/login")
                        .defaultSuccessUrl(defaultUrl,true)
                        .usernameParameter("userid")
                        .passwordParameter("userpw")
                        .permitAll()
                    .and()
                        .logout()
                        .logoutUrl("/auth/logout")
                        .logoutSuccessUrl("/auth/loginPage")
                        .permitAll();
        }
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring()
                    .antMatchers("/assets/**")
                    .antMatchers("/css/**")
                    .antMatchers("/images/**")
                    .antMatchers("/js/**")
                    .antMatchers("/service/**")
                    .antMatchers("/**/*.js")
                    .antMatchers("/**/*.jpg")
                    .antMatchers("/**/*.png")
                    .antMatchers("/**/*.css");
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
        }
    }
     Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
            if (authentication != null
                    && !authentication.getPrincipal().equals("anonymousUser")
                    && !(matcher.match("/actuator/**", request.getRequestURI())
                        ||matcher.match("/error/**", request.getRequestURI())
                        ||matcher.match("/auth/**", request.getRequestURI())
                        ||matcher.match("/menu/**", request.getRequestURI()))) {
                UserDto userInfo = (UserDto) authentication.getPrincipal();
                request.setAttribute("authUser", userInfo.getUserId());
                request.setAttribute("authUserInfo", userInfo);
    
                //api check
                ApiDto apiCheck = userInfo.getGrantApis().stream()
                        .filter(x -> matcher.match(x.getUriPath().trim(), request.getRequestURI()))
                        .findFirst()
                        .orElseGet(ApiDto::new);
    
                System.out.println("============ " + apiCheck.getUriPath());
                System.out.println("============ " + request.getRequestURI());
    
                if (apiCheck.getId() == null && !userInfo.getUserId().equals("root")) {
                    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        return;
                    } else {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    //                    response.sendRedirect("/portal/error/error401");
                        response.sendRedirect("/error/error401");
                        return;
                    }
                }
    
            } else {

    댓글

Designed by Tistory.