2016-01-20 5 views
1

У меня есть следующие Sprring веб-приложение:Весна пользовательских безопасности Войти URL

@Secured({"ROLE_ADMIN"}) 
@RequestMapping(value = "data/{id}", method = RequestMethod.GET) 
public Object getData(@RequestPath String id) 

@RequestMapping(value = "login", method = RequestMethod.GET) 
public Object login(@RequestParam String username, @RequestParam String password) 

В входе нужно вызвать другой сервер, передавать учетные данные и получить обратно роли, то пусть весна знать, чтобы использовать эти роли для входящего пользователя , После входа в систему клиент может использовать метод getData, если разрешает авторизацию ROLE_ADMIN.

Как реализовать это поведение с помощью java config?

UPDATE:

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    public AuthenticationProvider authenticationProvider; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .authorizeRequests() 
       .antMatchers("/login").permitAll() 
       .anyRequest().authenticated() 
      ; 
    } 


    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.authenticationProvider(authenticationProvider); 
    } 
} 

@Component 
public class CustomAuthenticationProvider implements AuthenticationProvider { 

    private static final Logger logger = LogFactory.getLogger(); 

    @Override 
    public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
     String name = authentication.getName(); 
     String password = authentication.getCredentials().toString(); 
     log.debug("name=" + name + " password=" + password); 
     List<GrantedAuthority> grantedAuths = new ArrayList<>(); 
     grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN")); 
     Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths); 
     return auth; 
    } 

    @Override 
    public boolean supports(Class<?> authentication) { 
     logger.debug("supports authentication=" + authentication); 
     return true; 
    } 
} 

public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { 
} 

Но, как я могу видеть из бревен CustomAuthenticationProvider.authenticate никогда не называется. Я что-то пропустил? Спасибо.

UPDATE 2: правильное решение для меня:

  1. Удалить Логин URL от конфигурации аутентификации
  2. добавить обработчик исключений, чтобы отключить перенаправление в случае ошибки аутентификации
  3. добавить обработчик успеха, чтобы отправить пользователю правильный ответ JSon
  4. использование http POST для приложения/логина
  5. @EnableGlobalMethodSecurity (secureEnabled = true) в веб-конфигурации, чтобы разрешить @Secured аннотацию в контроллере. Спасибо за все подсказки.

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeRequests() 
    **.anyRequest().authenticated()** 
    .and().formLogin() 
    .loginProcessingUrl("/login").usernameParameter("username") 
    .passwordParameter("password") 
    **.successHandler(authenticationSuccessHandler)**.failureHandler(authenticationFailureHandler) 
    .and().csrf().disable().**exceptionHandling() 
    .authenticationEntryPoint(errorsAuthenticationEntryPoint)**; 
} 

ответ

0

Вам нужно будет реализовать пользовательский AuthenticationProvider. Что-то вроде:

@Configuration 
@EnableWebMvcSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) throws Exception { 
    auth.authenticationProvider(customAuthenticationProvider()); 
} 

@Bean 
AuthenticationProvider customAuthenticationProvider() { 
    CustomAuthenticationProvider impl = new CustomAuthenticationProvider(); 
    impl.setUserDetailsService(customUserDetailsService()); 
    /* other properties etc */ 
    return impl ; 
} 

@Bean 
UserDetailsService customUserDetailsService() { 
    /* custom UserDetailsService code here */ 
} 

}

+0

Спасибо за ваш ответ. Я реализовал это, также добавил разрешение для URL-адреса для входа, но мой CustomAuthenticationProvider не работает. Я поставил там несколько журналов, и, как я вижу, его никогда не называют весной. – rholovakha

+0

Пожалуйста, просмотрите эту ссылку - она ​​объясняет все: http: //docs.spring.io/spring-security/site/docs/current/guides/html5/form.html –

3

Вы должны использовать WebSecurityConfigurerAdapter как это:

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
     .logout() 
      .logoutUrl("/myurl/logout") 
      .and() 
     .formLogin() 
      .loginPage("/myurl/login") 
      .defaultSuccessUrl("/myurl/login?success"); 
}  
} 

Каждая вещь объяснить в документации http://docs.spring.io/spring-security/site/docs/current/guides/html5/form.html

Смежные вопросы