Вход через токен доступа и обычная форма входа не работает - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь защитить свое приложение разными способами.1-й: api-часть (/ api / **) должна быть защищена с помощью oauth-токена 2-й: другие части должны быть защищены с помощью обычной формы входа в систему с именем пользователя и паролем.

С моим WebSecurityConfig я могу защититьчасть API.Но для обычного Маршрута / пользователя отображается форма входа в систему, но после отправки учетных данных входа ничего не происходит.

Надеюсь, вы можете дать мне подсказку, что я делаю не так?

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig {


    @Configuration
    @Order(1)
    @EnableResourceServer
    public static class ApiWebSecurityConfig extends ResourceServerConfigurerAdapter {

        @Value("${security.signing-key}")
        private String signingKey;

        @Value("${security.encoding-strength}")
        private Integer encodingStrength;

        @Value("${security.security-realm}")
        private String securityRealm;

        @Value("${security.jwt.resource-ids}")
        private String resourceIds;

        @Autowired
        private ResourceServerTokenServices tokenServices;


        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.antMatcher("/api/**").authorizeRequests()
            .antMatchers("/oauth/token").permitAll();

        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId(resourceIds).tokenServices(tokenServices);
        }

        @Bean
        public JwtAccessTokenConverter accessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            converter.setSigningKey(signingKey);
            return converter;
        }

        @Bean
        public TokenStore tokenStore() {
            return new JwtTokenStore(accessTokenConverter());
        }

        @Bean
        @Primary 
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
            defaultTokenServices.setTokenStore(tokenStore());
            defaultTokenServices.setSupportRefreshToken(true);
            return defaultTokenServices;
        }
    }

    @Configuration
    @Order(2)
    public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter {
        private static final String LOGIN_PROCESSING_URL = "/login";
        private static final String LOGIN_FAILURE_URL = "/login?error";
        private static final String LOGIN_URL = "/login";
        private static final String LOGOUT_SUCCESS_URL = "/logout";
        private static final String LOGIN_SUCCESS_URL = "/user";


        @Autowired
        private PasswordEncoder passwordEncoder;

        @Autowired
        private UserDetailsService userDetailsService;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
             http .antMatcher("/user").requestCache().requestCache(new
              CustomRequestCache())

              // Restrict access to our application. 
              .and().authorizeRequests()

              // Allow all flow internal requests.
              .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()

              // Allow all requests by logged in users.
              .anyRequest().hasAnyAuthority(Role.getAllRoles())

              // Configure the login page.
              .and().formLogin().loginPage(LOGIN_URL).permitAll().loginProcessingUrl(
              LOGIN_PROCESSING_URL) .failureUrl(LOGIN_FAILURE_URL)

              // Register the success handler that redirects users to the page they last
              //tried // to access 
              .successHandler(new
              SavedRequestAwareAuthenticationSuccessHandler())
              .defaultSuccessUrl(LOGIN_SUCCESS_URL,true)

              // Configure logout 
              .and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL);


        }


        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers(

                    //icons and images...
        }


        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Bean
        @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
        public User currentUser(UserRepository userRepository) {
            return userRepository.findByEmailIgnoreCase(SecurityUtils.getUsername());
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            super.configure(auth);
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
            // auth.userDetailsService(userDetailsService);
        }

        @Bean()
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

    }

}

...