2016-08-29 9 views
-1

私は春のOAuth2 loginFormとaccess_tokenを使って認証しています。しかし、私がログインすると、access_token認証が必要なリソースサーバーにアクセスすることができません。OAuth2からのログイン時にAccessTokenを取得してください。LoginFrom

ログイン時にaccess_tokenを取得するにはどうすればよいですか?

自分でaccess_tokenを手動で作成する必要がありますか?

私は春のセキュリティとconfigのことです:

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private SpringDataMyBatisUserDetailsService userDetailsService; 

    @Override 
    @Autowired 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
     .userDetailsService(this.userDetailsService) 
     .passwordEncoder(Manager.PASSWORD_ENCODER); 
    } 

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

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class); 
    } 

    @Order(1) 
    @Configuration 
    @EnableAuthorizationServer 
    public static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { 

     private final AuthenticationManager authenticationManager; 
     @Autowired 
     private TokenStore tokenStore; 
     @Autowired 
     private SpringDataMyBatisClientDetailsService clientDetailsService; 

     @Autowired 
     public AuthorizationServerConfig(AuthenticationManager authenticationManager) { 
      this.authenticationManager = authenticationManager; 
     } 

     /** 
     * Defines the security constraints on the token endpoints /oauth/token_key and /oauth/check_token 
     * Client credentials are required to access the endpoints 
     * 
     * @param oauthServer 
     * @throws Exception 
     */ 
     @Override 
     public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 
      oauthServer 
//   .passwordEncoder(Client.PASSWORD_ENCODER) 
      .tokenKeyAccess("permitAll()") 
      .checkTokenAccess("isAuthenticated()"); 
     } 

     /** 
     * Defines the authorization and token endpoints and the token services 
     * 
     * @param endpoints 
     * @throws Exception 
     */ 
     @Override 
     public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 
      endpoints 
      .authenticationManager(this.authenticationManager) 
      .tokenEnhancer(tokenEnhancer()) 
      .tokenStore(tokenStore); 
     } 

     @Override 
     public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
      clients 
      .withClientDetails(clientDetailsService); 
     } 

     @Bean 
     public TokenEnhancer tokenEnhancer() { 
      return new CustomTokenEnhancer(); 
     } 

    } 

    @Order(3) 
    @Configuration 
    @EnableResourceServer 
    public static class ApiResources extends ResourceServerConfigurerAdapter { 

     @Autowired 
     private RestAuthenticationEntryPoint restAuthenticationEntryPoint; 
     @Autowired 
     private AuthenticationSuccessHandler successHandler; 
     @Autowired 
     private AuthenticationFailureHandler failureHandler; 
     @Autowired 
     private TokenStore tokenStore; 

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

     @Override 
     public void configure(HttpSecurity http) throws Exception { 
      http 
      .antMatcher("/api/**") 
      .exceptionHandling() 
      .authenticationEntryPoint(restAuthenticationEntryPoint) 
      .and() 
      .authorizeRequests() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .successHandler(successHandler) 
       .failureHandler(failureHandler) 
       .and() 
      .logout(); 
     } 

    } 

    @Order(4) 
    @Configuration 
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 
      http 
      .csrf().disable() 
      .authorizeRequests() 
       .anyRequest().authenticated() 
       .and() 
      .formLogin() 
       .loginPage("/authention/login") 
       .defaultSuccessUrl("/", true) 
       .failureUrl("/authention/login?error") 
       .permitAll() 
       .and() 
      .logout() 
       .logoutSuccessUrl("/authention/login?success") 
       .and() 
      .sessionManagement() 
       .sessionFixation().migrateSession(); 
     } 

    } 

    @Bean 
    public static AuthenticationSuccessHandler myAuthenticationSuccessHandler() { 
     return new SavedRequestAwareAuthenticationSuccessHandler(); 
    } 

    @Bean 
    public static AuthenticationFailureHandler myAuthenticationFailureHandler() { 
     return new SavedRequestAwareAuthenticationFailureHandler(); 
    } 

} 

答えて

0

アプリで、バネのOAuthを設定するときは、トークンを取得するためにREST APIにアクセスすることができ、トークンを取り消すなど 基本的なOAuthの構成の場合、このlinkを参照してください。スプリングブートアプリケーションの場合アプリケーションを構成した後

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
@ComponentScan(basePackages = {"com.test.config"}) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 


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

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .csrf() 
      .disable(); 
    http 
      .authorizeRequests() 
      .anyRequest().access("#oauth2.hasScope('read')") 
      .and() 
      .exceptionHandling() 
      .authenticationEntryPoint(oauthAuthenticationEntryPoint()) 
      .accessDeniedHandler(oAuth2AccessDeniedHandler()); 
    http 
      .formLogin() 
      .loginPage("/login") 
      .failureUrl("/") 
      .permitAll() 
      .and() 
      .logout() 
      .logoutSuccessUrl("/login") 
      .permitAll(); 
} 
} 

@Configuration 
@EnableAuthorizationServer 
public class OAuth2AuthorizationServerConfig extends  AuthorizationServerConfigurerAdapter { 

@Override 
public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 
    clients 
      .inMemory() 
      .withClient("hello") 
      .authorizedGrantTypes("password", "refresh_token") 
      .authorities("ROLE_APP") 
      .scopes("read", "write") 
      .secret("secret"); 
    } 
} 

とSecurityConfigクラス:そしてまたAPI reference

サンプルOAuth2AuthorizationServerConfigを通過します。以下のようにREST APIにアクセスできます。以下に示すように、それが成功した後、トークンが生成されている場合、これはユーザーを認証します

localhost:8080/oauth/token?grant_type=password&client_id=hello&client_secret=secret&username=admin&password=password

:あなたはこのURLにアクセスする必要があるトークンを取得するための

  1. { 
        "access_token": "0307d70f-e3da-40f4-804b-f3a8aba4d8a8", 
        "token_type": "bearer", 
        "refresh_token": "daf21f97-f425-4245-8e47-19e4c87000e8", 
        "expires_in": 119, 
        "scope": "read write" 
    } 
    
    1. このトークンを取得すると、このトークンを渡すだけでアプリケーションのREST APIにアクセスできます。たとえば、「/ hello」というURLがある場合は、上記の手順で取得したトークンを追加する要求を に入力します。

      "http://localhost:8080/hello?access_token=0307d70f-e3da-40f4-804b-f3a8aba4d8a8"

+0

こんにちは、最初にあなたの答えをありがとう。私はすでにログに記録されているユーザーだけが残りのAPIにアクセスすることもできます。 – WhiteWater

+0

それは私が私の答えで言及したものです。まず、ユーザーが認証され、トークンが生成されます。ユーザーがREST APIにアクセスするには、有効なトークンを指定する必要があります。 '?access_token = [ここに生成トークン]'をURLに追加する必要があります。トークンが有効な場合のみ、ユーザーはREST APIにアクセスできます。 – CodingFreak

+0

'protected void configure(HttpSecurity http)'メソッドの 'http.authorizeRequests()'は、ユーザのURLへのアクセスをカスタマイズすることができます。 – CodingFreak

関連する問題