복붙노트

[SPRING] 스프링 보안 oauth2 및 양식 로그인 구성

SPRING

스프링 보안 oauth2 및 양식 로그인 구성

내 프로젝트는 JSF 관리 패널과 RESTfull 서비스의 두 가지 부분으로 구성됩니다. 사용자가 탐색하는 URL에 따라 다른 인증 방법을 사용하도록 스프링 보안을 설정하려고합니다.

요구 사항은 다음과 같습니다.

별도의 구성 자체가 작동, 문제는 하나의 구성에서 두 가지 모두를 결합하려고 할 때입니다.이 경우 REST 공급자가 요청을 받고 관리 URL (이 경우 요청을받는 경우에도 각 요청을 인증합니다. 봄 보안 주문서에서 문서화 됨).

샘플 구성은 다음과 같습니다.

이러한 구성은 다른 클래스에 존재하며 순서는 수동으로 설정됩니다.

누구든지이 문제에 대한 해결책을 갖고 있습니까?

베스트,

해결법

  1. ==============================

    1.보안 구성을 조정하려고했습니다. 안타깝게도 누락 된 참조 응용 프로그램 때문에이 구성의 유효성을 검사 할 수 없습니다.

    보안 구성을 조정하려고했습니다. 안타깝게도 누락 된 참조 응용 프로그램 때문에이 구성의 유효성을 검사 할 수 없습니다.

    아마 그것은 당신을 도울 수 있습니다 :

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserRepository userRepository;
    
        @Autowired
        private PasswordEncoder passwordEncoder;
    
        @Autowired
        protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(new UserDetailsService() {
                @Override
                public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                    User user = userRepository.findOneByUsername(s);
    
                    if (null == user) {
                        throw new UsernameNotFoundException("The user with email " + s + " was not found");
                    }
    
                    return (UserDetails) user;
                }
            }).passwordEncoder(passwordEncoder);
        }
    
        @Override
        public void configure(WebSecurity webSecurity) throws Exception {
            webSecurity
                    .ignoring()
                    .antMatchers("/resources/**"
                            , "/templates/**"
                            , "/login"
                            , "/logout"
                            , "/ui/**"
                            , "/401.html"
                            , "/404.html"
                            , "/500.html");
        }
    
        @Configuration
        @EnableAuthorizationServer
        public static class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
    
            @Autowired
            private AuthenticationManager authenticationManager;
    
            @Bean
            public JwtAccessTokenConverter accessTokenConverter() {
                return new JwtAccessTokenConverter();
            }
    
            @Override
            public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
                oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')").checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
            }
    
            @Override
            public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
                endpoints.authenticationManager(authenticationManager).accessTokenConverter(accessTokenConverter());
            }
    
    
            @Override
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.inMemory()
                        .withClient("xxx")
                        .resourceIds("xxx")
                        .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
                        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
                        .scopes("read", "write", "trust", "update")
                        .accessTokenValiditySeconds(xxx)
                        .refreshTokenValiditySeconds(xxx)
                        .secret("xxx");
    
            }
        }
    
        @Configuration
        @Order(1)
        public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    
            @Override
            public void configure(HttpSecurity http) throws Exception {
                http
                        .csrf().disable()
                        .authorizeRequests()
                        .antMatchers("/ui/admin.xhtml").hasAnyAuthority("admin", "ADMIN")
                        .antMatchers("/thymeleaf").hasAnyAuthority("admin", "ADMIN")
                        .and()
                        .formLogin()
                        .loginPage("/login")
                        .defaultSuccessUrl("/ui/index.xhtml")
                        .failureUrl("/login?error=1")
                        .permitAll()
                        .and()
                        .logout()
                        .permitAll()
                        .and()
                        .rememberMe()
                        .and().exceptionHandling().accessDeniedPage("/error/403");
            }
        }
    
        @Order(2)
        @Configuration
        @EnableResourceServer
        public static class CustomResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
    
            @Bean
            ApplicationListener<AbstractAuthorizationEvent> loggerBean() {
                return new AuthenticationLoggerListener();
            }
    
            @Bean
            AccessDeniedHandler accessDeniedHandler() {
                return new AccessDeniedExceptionHandler();
            }
    
            @Bean
            AuthenticationEntryPoint entryPointBean() {
                return new UnauthorizedEntryPoint();
            }
    
            @Override
            public void configure(HttpSecurity http) throws Exception {
                ContentNegotiationStrategy contentNegotiationStrategy = http.getSharedObject(ContentNegotiationStrategy.class);
                if (contentNegotiationStrategy == null) {
                    contentNegotiationStrategy = new HeaderContentNegotiationStrategy();
                }
                MediaTypeRequestMatcher preferredMatcher = new MediaTypeRequestMatcher(contentNegotiationStrategy,
                        MediaType.APPLICATION_FORM_URLENCODED,
                        MediaType.APPLICATION_JSON,
                        MediaType.MULTIPART_FORM_DATA);
    
                http.authorizeRequests()
                        .and()
                        .anonymous().disable()
                        .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                        .and().httpBasic()
                        .and()
                        .exceptionHandling()
                        .accessDeniedHandler(accessDeniedHandler()) // handle access denied in general (for example comming from @PreAuthorization
                        .authenticationEntryPoint(entryPointBean()) // handle authentication exceptions for unauthorized calls.
                        .defaultAuthenticationEntryPointFor(entryPointBean(), preferredMatcher)
                        .and()
                        .authorizeRequests()
                        .antMatchers("/api/**").fullyAuthenticated();
            }
        }
    }
    
  2. from https://stackoverflow.com/questions/28908946/spring-security-oauth2-and-form-login-configuration by cc-by-sa and MIT license