401 - 访问此资源需要完全身份验证。同时获取刷新令牌

时间:2016-08-03 15:02:34

标签: spring oauth-2.0

我正在尝试使用Java配置实现Spring Security OAuth2。

我的用例需要使用密码grant_type。

到目前为止,我已经配置了这个,而不需要web.xml,并且希望保持这种方式。

我试图获取刷新令牌和访问令牌,但它会抛出401 Unauthorized。

这是一个网址:

http://localhost:9090/oauth-authincation-using-annotation/oauth/token?grant_type=password&client_id=abc&username=user&password=password

enter image description here 并得到一个错误 401未经授权。

我正在使用的版本:

  

Spring Framework:4.1.6

     

Spring Security:4.0.1

     

Spring Security OAuth:2.0

安全等级

Oauth2ServerConfig

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

@Configuration
public class OAuth2ServerConfig {


    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter{

        @Autowired 
        private TokenStore tokenStore;

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception{

            clients
                .inMemory()
                    .withClient("abc")

                    .scopes("read", "write")
                    .authorities("USER")
                    .authorizedGrantTypes("password", "refresh_token")
                    .accessTokenValiditySeconds(60)
                    .refreshTokenValiditySeconds(3600);

        }

        @Bean
        public TokenStore tokenStore() {

           return new InMemoryTokenStore();

        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception{

            endpoints
                .tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET);

        }

        @Override 
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {

        }
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources){

            resources.resourceId("SomeResourseId").stateless(false);

        }

        @Override
        public void configure(HttpSecurity http) throws Exception{

            http
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
                .authorizeRequests()
                    .antMatchers("/").access("#oauth2.hasScope('read')");
        }
    }
}

SecurityConfig

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

 auth.
            inMemoryAuthentication()
            .withUser("user")
            .password("password")
            .roles("USER");

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/oauth2/client").authenticated()
                .and().httpBasic();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

SpringMvcInitializer

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.harish.config.AppConfig;

public class SpringMvcInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {

        return new Class[] { AppConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {

        return new String[] { "/" };
    }

}

AppConfig

import java.util.Properties;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.harish.web.*"})
@EnableTransactionManagement
@PropertySource("classpath:database.properties")
@ImportResource({
      "classpath*:**/applicationContext*.xml"
    })
@Import({ SecurityConfig.class ,OAuth2ServerConfig.class})
public class AppConfig {

  private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
  private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
  private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
  private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
  private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
  private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
  private static final String PROPERTY_NAME_HIBERNATE_FORMAT_SQL = "hibernate.format_sql";
  private static final String PROPERTY_NAME_HIBERNATE_HBM2DLL_AUTO = "hibernate.hbm2ddl.auto";
  private static final String PROPERTY_NAME_HIBERNATE_DEFAULT_SCHEMA = "hibernate.default_schema";
  private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";


  @Resource
  private Environment env;

  @Bean(name = "dataSource")
  public DriverManagerDataSource dataSource()
  {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(this.env.getProperty(PROPERTY_NAME_DATABASE_DRIVER));
    dataSource.setUrl(this.env.getProperty(PROPERTY_NAME_DATABASE_URL));
    dataSource.setUsername(this.env.getProperty(PROPERTY_NAME_DATABASE_USERNAME));
    dataSource.setPassword(this.env.getProperty(PROPERTY_NAME_DATABASE_PASSWORD));
    return dataSource;

  }

  @Bean
  public InternalResourceViewResolver viewResolver()
  {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
  }

  @Bean
  public LocalSessionFactoryBean sessionFactory()
  {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(this.dataSource());
    sessionFactory.setPackagesToScan(this.env
        .getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
    sessionFactory.setHibernateProperties(this.hibProperties());
    //sessionFactory.set
    return sessionFactory;
  }

  @Bean
  @Autowired
  public HibernateTransactionManager transactionManager(SessionFactory sessionFactory)
  {
    HibernateTransactionManager txManager = new HibernateTransactionManager();
    txManager.setSessionFactory(sessionFactory);

    return txManager;
  }

  private Properties hibProperties()
  {
    Properties properties = new Properties();
    properties.put(PROPERTY_NAME_HIBERNATE_DIALECT,
        this.env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
    properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,
        this.env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
    properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL,
        this.env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
    properties.put(PROPERTY_NAME_HIBERNATE_HBM2DLL_AUTO,
        this.env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DLL_AUTO));
    properties.put(PROPERTY_NAME_HIBERNATE_DEFAULT_SCHEMA,
        this.env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DEFAULT_SCHEMA));
    return properties;
  }

}

0 个答案:

没有答案