从OAuth2登录时获取AccessToken登录

时间:2016-08-29 15:28:07

标签: spring spring-boot spring-security-oauth2

我使用spring OAuth2 loginForm和access_token方式进行身份验证。但是当我登录时,我无法访问需要access_token授权的资源服务器。

登录时如何获得access_token?

我应该自己手动创建access_token吗?

我使用spring security配置的是:

@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();
    }

}

1 个答案:

答案 0 :(得分:0)

在应用程序中配置spring-oauth时,您可以访问REST API以获取令牌,撤消令牌等。 请参阅此link了解Spring启动应用程序的基本oauth配置。并且还要查看API reference

示例OAuth2AuthorizationServerConfig:

@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类:

@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();
}
}

配置应用程序后。您可以按如下方式访问REST API。

  1. 要获取令牌,您需要访问此网址:

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

  2. 这将验证用户是否成功,然后生成令牌,如下所示:

    {
        "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。例如,如果你有一个URL“/ hello”那么 请求附加您通过上述步骤获得的令牌的请求。

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