2015-11-20 4 views
3

Работа над внедрением Oauth2 с пружиной. Я хочу, чтобы реализовать неявную рабочий процесс:Spring Oauth2 неявный поток

Мой конфигурационный файл:

@Configuration 
@EnableAutoConfiguration 
@RestController 
public class App { 

    @Autowired 
    private DataSource dataSource; 

    public static void main(String[] args) { 
     SpringApplication.run(App.class, args); 
    } 

    @RequestMapping("/") 
    public String home() { 
     return "Hello World"; 
    } 

    @Configuration 
    @EnableResourceServer 
    protected static class ResourceServer extends ResourceServerConfigurerAdapter { 

     @Autowired 
     private TokenStore tokenStore; 

     @Override 
     public void configure(ResourceServerSecurityConfigurer resources) 
       throws Exception { 
      resources.tokenStore(tokenStore); 
     } 

     @Override 
     public void configure(HttpSecurity http) throws Exception { 
      // @formatter:off 
     http.authorizeRequests().antMatchers("/oauth/token").authenticated() 
       .and() 
       .authorizeRequests().anyRequest().permitAll() 
       .and() 
       .formLogin().loginPage("/login").permitAll() 
       .and() 
       .csrf().disable(); 
     } 

    } 

    @Configuration 
    @EnableAuthorizationServer 
    protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter { 

     @Autowired 
     private AuthenticationManager auth; 

     private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 

     @Bean 
     public JdbcTokenStore tokenStore() { 
      return new JdbcTokenStore(DBConnector.dataSource); 
     } 

     @Bean 
     protected AuthorizationCodeServices authorizationCodeServices() { 
      return new JdbcAuthorizationCodeServices(DBConnector.dataSource); 
     } 

     @Override 
     public void configure(AuthorizationServerSecurityConfigurer security) 
       throws Exception { 
      security.passwordEncoder(passwordEncoder); 
     } 

     @Override 
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) 
       throws Exception { 
      endpoints.authorizationCodeServices(authorizationCodeServices()) 
        .authenticationManager(auth).tokenStore(tokenStore()) 
        .approvalStoreDisabled();    
     } 

     @Override 
     public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
      // @formatter:off 
      clients.jdbc(DBConnector.dataSource) 
        .passwordEncoder(passwordEncoder) 
        .withClient("my-trusted-client") 
        .secret("test") 
        .authorizedGrantTypes("password", "authorization_code", 
          "refresh_token", "implicit") 
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT") 
        .scopes("read", "write", "trust") 
        .resourceIds("oauth2-resource") 
        .accessTokenValiditySeconds(0); 

      // @formatter:on 
     } 

    } 

    @Autowired 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
     // @formatter:off 
     auth.jdbcAuthentication().dataSource(DBConnector.dataSource).withUser("dave") 
       .password("secret").roles("USER"); 

     // @formatter:on 
    } 

} 

Это работает до сих пор. Пользователь также генерируется в базе данных.

Проблема следующая. Когда я пытаюсь сделать следующие просьбы:

http://localhost:8080/oauth/token?grant_type=authorization_code&client_id=my-trusted-client&username=dave&password=secret

Я всегда получаю всплывающее окно (аутентификация) с просьбой меня ввести имя пользователя и пароль. Но не важно, что я туда вхожу, я никогда не прохожу. Так что там не так?

Я хотел бы иметь это, что, когда я назову этот URL-адрес, я вернусь к своему access_token.

ответ

4

В случае неявного потока все токены будут сгенерированы с помощью URL-адреса авторизации вместо символа токена. поэтому вы должны нажать .../oauth/authorize конечную точку с неявным типом ответа. т.е.

../oauth/authorize?response_type=implicit&client_id=trusted_client&redirect_uri=<redirect-uri-of-client-application>. 

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

@Override 
     public void configure(HttpSecurity http) throws Exception { 
      // @formatter:off 
     http.authorizeRequests().antMatchers("/oauth/authorize").authenticated() 
       .and() 
       .authorizeRequests().anyRequest().permitAll() 
       .and() 
       .formLogin().loginPage("/login").permitAll() 
       .and() 
       .csrf().disable(); 
     } 
+2

Почему вы отключите подделку подпроса? – Benedictus

+1

Неявное значение потока ответов 'response_type' должно быть установлено« токен »[см. [This] (https://tools.ietf.org/html/rfc6749#section-4.2.1) –

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