2016-07-26 120 views
2

我們正在開發Spring 4 REST/JSON API,但我們需要使用自定義身份驗證服務對第三方服務進行身份驗證。春季安全4. JSON REST與自定義身份驗證和授權

限制:我們不要想要求用戶輸入用戶名/密碼。我們使用「cookie」進行身份驗證(與請求發起人一起發送)。我們需要在後臺進行身份驗證。 (可能聽起來很奇怪,但情況就是這樣)。

我們可以使用註冊自定義認證/授權請求過濾器來實現。但是這讓我們失去了我們打算在之後使用的彈簧「​​授權」模塊的力量。

所以我們所做的事情到現在爲止,寫了定製WebSecurityConfigurerAdapter與我們自己的自定義的AuthenticationProvider的UserDetailsS​​ervice但這些配置似乎並沒有工作。

應用程序不進去AuthenticationProvider.authenticate

這裏是我們不得不配置。

AuthenticationProvider.java

@Service 
public class AuthenticationService implements AuthenticationProvider, UserDetailsService { 

     @Override 
    public Authentication authenticate(Authentication auth) throws AuthenticationException { 
     // DOESN'T ENTER THIS FUNCTION 
     // do authentication stuff 
    } 


    @Override 
    public boolean supports(Class<?> authentication) { 
     // JUST FOR TESTING 
     return true; 
    } 


    @Override 
    public UserDetails loadUserByUsername(String username) 
      throws UsernameNotFoundException { 

     // DOESN'T ENTER THIS METHOD 
     return null; 
    } 
} 

SecurityConfig.java:

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityConfig.class); 

    @Autowired 
    private AuthenticationService authService; 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.ignoring().antMatchers("/ignoredURL/**"); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable() //HTTP with Disable CSRF 
       .authorizeRequests() 
        .antMatchers("/api/XYZ/**").hasRole("ADMIN") 
        .anyRequest().authenticated(); 
     // adding ".httpBasic()" automatically prompts user for username/password 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     // THIS IS NOT TYPO, I use one service implements both interfaces. 
     auth.userDetailsService(authService); 
     auth.authenticationProvider(authService); 
    } 


} 

回答

1

加入2多個類(延伸AbstractPreAuthenticatedProcessingFilter和另一類CustomUser器具UserDetails濾波器)固定,然後使我AuthenticaitonService實現彈簧UserDetailsService這裏是細節:

請對what this filter does and how it works

1-看看創建AbcFilter延伸春天AbstractPreAuthenticatedProcessingFilter

2-覆蓋 「getPreAuthenticatedPrincipal」。此方法提取了cookie值並將其返回。 (無論你在這裏返回的對象是你在UserDetailsService.loadUserByUsername中得到的參數)。

3-修改我的服務來實現彈簧UserDetailsServiceloadUserByUsername裏面做了所有驗證邏輯,並將所有登錄用戶設置爲CustomUser對象。然後返回它。如果請求匹配/api/XYZ/**,Spring會調用您的CustomUser.getAuthorities並嘗試在那裏找到ADMIN角色。