SpringSecurity - Custom automatic authentication

后端 未结 2 1260
不思量自难忘°
不思量自难忘° 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 01:59

    Yes, Pre-Authentication Scenarios are exactly what you are looking for.

    It seems that those object are expected to be used when the principal is already in session, put by some previous authentication machanism (is it right?).

    Not really, you can use Pre-Authentication to create PreAuthenticatedAuthenticationToken from request, as you want. Just do few things I described in another question.

    First extend AbstractPreAuthenticatedProcessingFilter to obtain username and roles from request:

    public class MyPreAuthenticatedProcessingFilter
        extends AbstractPreAuthenticatedProcessingFilter {
    
      public MyPreAuthenticatedProcessingFilter(
          AuthenticationManager authenticationManager) {
        setAuthenticationDetailsSource(new MyAuthenticationDetailsSource());
      }
    
      @Override
      protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        return "Anonymous";
      }
    
      @Override
      protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        return "N/A";
      }
    
      public static class MyAuthenticationDetailsSource implements 
          AuthenticationDetailsSource<HttpServletRequest, MySessionUserDetails> {
        // roles probably should be encrypted somehow
        static final String ROLES_PARAMETER = "pre_auth_roles";
    
        @Override
        public MySessionUserDetails buildDetails(HttpServletRequest req) {
          // create container for pre-auth data
          return new MySessionUserDetails(req.getParameter(ROLES_PARAMETER));
        }
      }
    }
    

    MySessionUserDetails class will split spring with roles to List of SimpleGrantedAuthority or any other GrantedAuthority implementation. Also, List is recommended and superior to GrantedAuthority[].

    Second, implement AuthenticationUserDetailsService:

    public class MyPreAuthenticatedUserDetailsService implements 
        AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> {
    
      @Override
      public UserDetails loadUserDetails(PreAuthenticatedAuthenticationToken token)
          throws UsernameNotFoundException {
        MySessionUserDetails sessionUserDetails =
            (MySessionUserDetails) token.getDetails();
        List<GrantedAuthority> authorities = sessionUserDetails.getAuthorities();
        return new User(token.getName(), "N/A", true, true, true, true, authorities);
      }
    }
    

    Then in your XML connect blocks together:

    <security:http use-expressions="true">
      <security:intercept-url pattern="/**" access="isAuthenticated()" />
      <security:custom-filter position="PRE_AUTH_FILTER"
          ref="myPreAuthenticationFilter" />
    </security:http>
    
    <bean id="myPreAuthenticationFilter"
        class="com.example.MyPreAuthenticatedProcessingFilter">
      <property name="authenticationManager" ref="authenticationManager" />
    </bean>
    
    <bean id="preauthAuthProvider" class="org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider">
      <property name="preAuthenticatedUserDetailsService">
        <bean class="com.example.MyPreAuthenticatedUserDetailsService" />
      </property>
    </bean>
    
    <security:authentication-manager alias="authenticationManager">
      <security:authentication-provider ref="preauthAuthProvider" />
    </security:authentication-manager>
    

    And voila! You should have authenticated User principal to use in your application.

    Code I written here requires Spring Security 3.1 which I strongly recommend if you're about to using it (it does requrire Spring 3.0.7+). Also, Spring Security reference manual is your friend!

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题