SpringSecurity - Custom automatic authentication

后端 未结 2 1262
不思量自难忘°
不思量自难忘° 2020-12-13 01:19

This is my scenario:

  • a web-app perform a sort-of SSO for many applications
  • logged-in user than click on a link and the app makes a post with user info
2条回答
  •  半阙折子戏
    2020-12-13 02:03

    For sake of completeness, in Spring Security 4 things are slightly changed. For example, the Java configuration is highly recommended. In this way, it's easier to integrate with Spring Boot.

    It follows the Java Configuration that is equivalent to the XML configuration given in the above answers.

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.addFilterBefore(customAuthFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .authenticationProvider(preauthAuthProvider())
                .authorizeRequests()
                .anyRequest().authenticated();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.authenticationProvider(preauthAuthProvider());
        }
    
        @Bean
        public PreAuthenticatedAuthenticationProvider preauthAuthProvider() {
            PreAuthenticatedAuthenticationProvider preauthAuthProvider =
                new PreAuthenticatedAuthenticationProvider();
                    preauthAuthProvider.setPreAuthenticatedUserDetailsService(
                        userDetailsServiceWrapper());
            return preauthAuthProvider;
        }
    
        @Bean
        public OnlyRolesPreAuthenticatedUserDetailsService userDetailsServiceWrapper() {
            OnlyRolesPreAuthenticatedUserDetailsService service =
                new MyPreAuthenticatedUserDetailsService();
            return service;
        }
    
        @Bean
        public MyPreAuthenticatedProcessingFilter customAuthFilter() throws Exception {
            MyPreAuthenticatedProcessingFilter filter = new MyPreAuthenticatedProcessingFilter();
            filter.setAuthenticationManager(authenticationManager());
            return filter;
        }
    }
    

    I think that the above code is worth, because examples in internet are very basic and the Spring documentation lacks of such details.

提交回复
热议问题