我的休息服务无法识别授权:持票人

时间:2017-08-28 16:17:58

标签: java spring rest oauth spring-java-config

我只是改为java配置,但我的其他服务没有认识到“授权:承载”而我总是得到401

我的尝试:

  • 放置@EnableResourceServer注释,其余API工作正常,但我开始在登录页面中有一个“访问此资源需要完全身份验证”消息(xml)

  • 放入@EnableResourceServer并在“SecurityConfigurationFrom”中将@order更改为1,同样的问题是识别授权:持票人

OAuth2AuthorizationServerConfig:

    package com.xaxax.xa.api.config;

    import com.xaxax.xa.core.security.CheckTokenEndpoint;
    import com.xaxax.xa.core.security.EmptyPasswordEncoder;
    import com.xaxax.xa.core.security.UserApprovalHandler;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationProvider;
    import org.springframework.security.authentication.ProviderManager;
    import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    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.configurers.AuthorizationServerEndpointsConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
    import org.springframework.security.oauth2.provider.ClientDetailsService;
    import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
    import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
    import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

    import javax.sql.DataSource;
    import java.util.ArrayList;
    import java.util.List;

    @Configuration
    @EnableAuthorizationServer
    public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private UserDetailsService userDetailsServiceImpl;

        @Autowired
        private DataSource dataSource;


        @Bean
        public ClientDetailsService clientDetails (){
            JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(this.dataSource);
            return jdbcClientDetailsService;
        }

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


        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Bean
        public AuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
            daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
            daoAuthenticationProvider.setUserDetailsService(this.userDetailsServiceImpl);
            daoAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
            return daoAuthenticationProvider;
        }

        @Bean
        public EmptyPasswordEncoder emptyPasswordEncoder(){
            return new EmptyPasswordEncoder();
        }


        @Bean
        public AuthenticationProvider noPasswordAuthenticationProvider() {
            DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
            daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
            daoAuthenticationProvider.setUserDetailsService(this.userDetailsServiceImpl);
            daoAuthenticationProvider.setPasswordEncoder(this.emptyPasswordEncoder());
            return daoAuthenticationProvider;
        }

        @Bean
        public DefaultOAuth2RequestFactory oAuth2RequestFactory(){

            DefaultOAuth2RequestFactory oAuth2RequestFactory = new DefaultOAuth2RequestFactory(this.clientDetails());
            return oAuth2RequestFactory;

        }

        @Bean
        public UserApprovalHandler userApprovalHandler(){
            UserApprovalHandler userApprovalHandler = new UserApprovalHandler();
            userApprovalHandler.setTokenStore(this.tokenStore());
            userApprovalHandler.setRequestFactory(this.oAuth2RequestFactory());
            return userApprovalHandler;
        }


        @Bean
        public DefaultTokenServices tokenServices(){
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setTokenStore(this.tokenStore());
            tokenServices.setSupportRefreshToken(true);
            tokenServices.setClientDetailsService(this.clientDetails());
            return tokenServices;
        }

        @Bean
        public CheckTokenEndpoint checkTokenEndpoint(){
            CheckTokenEndpoint checkTokenEndpoint = new CheckTokenEndpoint();
            checkTokenEndpoint.setTokenServices(this.tokenServices());
            return checkTokenEndpoint;
        }



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

            clients.inMemory().withClient("xaxax");
            clients.withClientDetails(this.clientDetails());

        }

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

            List<AuthenticationProvider>  listAuthenticationProvider = new ArrayList<>();

            listAuthenticationProvider.add(this.authenticationProvider());

            ProviderManager providerManager = new ProviderManager(listAuthenticationProvider);

            endpoints
                    .tokenStore(this.tokenStore())
                    .tokenServices(tokenServices())
                    .userApprovalHandler(userApprovalHandler())
                    .authenticationManager(providerManager)
                    .setClientDetailsService(clientDetails());

        }

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

            oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();

        }


    }

SecurityConfiguration:

package com.xaxax.xa.api.config;

import com.xaxax.xa.api.handler.LoginFailureHandler;
import com.xaxax.xa.api.handler.TokenLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
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;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.ArrayList;
import java.util.List;

@Configuration
@Import(OAuth2AuthorizationServerConfig.class)
@EnableWebSecurity
@EnableResourceServer
public class SecurityConfiguration {


    @Autowired
    private TokenLogoutSuccessHandler tokenLogoutSuccessHandler;

    @Autowired
    private AuthenticationSuccessHandler loginSuccessDBHandler; // AuthenticationSuccessHandler

    @Autowired
    private OAuth2AuthorizationServerConfig oAuth2AuthorizationServerConfig;


    @Bean
    public LoginFailureHandler authenticationFailureHandler(){
        return new LoginFailureHandler();
    }

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver(){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    @Bean
    public MappingJackson2JsonView mappingJackson2JsonView(){
        MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
        mappingJackson2JsonView.setExtractValueFromSingleKeyModel(true);
        return mappingJackson2JsonView;
    }

    @Bean
    public ContentNegotiatingViewResolver viewResolvers(){

        ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();

        List<ViewResolver> viewResolvers = new ArrayList<>();
        viewResolvers.add(internalResourceViewResolver());

        List<View>  listView = new ArrayList<>();
        listView.add(mappingJackson2JsonView());

        contentNegotiatingViewResolver.setViewResolvers(viewResolvers);
        contentNegotiatingViewResolver.setDefaultViews(listView);
        return contentNegotiatingViewResolver;

    }


    @Bean
    public OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint(){
        OAuth2AuthenticationEntryPoint clientAuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        clientAuthenticationEntryPoint.setRealmName("xaxax/client");
        clientAuthenticationEntryPoint.setTypeName("Basic");
        return clientAuthenticationEntryPoint;
    }


    @Bean
    public ClientDetailsUserDetailsService clientDetailsUserService(){
        ClientDetailsUserDetailsService clientDetailsUserService = new ClientDetailsUserDetailsService(this.oAuth2AuthorizationServerConfig.clientDetails());
        return clientDetailsUserService;
    }


    @Bean
    public OAuth2AccessDeniedHandler oauthAccessDeniedHandler(){
        OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler = new OAuth2AccessDeniedHandler();
        return oAuth2AccessDeniedHandler;
    }

    @Bean
    public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter(){
        ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = new ClientCredentialsTokenEndpointFilter();

        List<AuthenticationProvider>  listAuthenticationProvider = new ArrayList<>();

        listAuthenticationProvider.add(this.oAuth2AuthorizationServerConfig.authenticationProvider());

        ProviderManager providerManager = new ProviderManager(listAuthenticationProvider);

        clientCredentialsTokenEndpointFilter.setAuthenticationManager(providerManager);

        return clientCredentialsTokenEndpointFilter;
    }

    @Configuration
    @Order(10)
    public static class SecurityConfigurationFrom extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityConfiguration securityConfiguration;

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

            ResourceServerSecurityConfigurer resources = new ResourceServerSecurityConfigurer();
            resources.tokenStore(securityConfiguration.oAuth2AuthorizationServerConfig.tokenStore());
            resources.tokenServices(securityConfiguration.oAuth2AuthorizationServerConfig.tokenServices());

           // @formatter:off
            http
                    .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                    .and()
                        .anonymous()
                    .and()
                        .authenticationProvider(securityConfiguration.oAuth2AuthorizationServerConfig.authenticationProvider())
                        .addFilterBefore(securityConfiguration.clientCredentialsTokenEndpointFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                        .authorizeRequests()
                            .antMatchers("/oauth/token/**").permitAll()
                            .antMatchers("/oauth/authorize/**").permitAll()
                            .antMatchers("/oauth/principal/**").hasRole("USER")
                            .antMatchers("/login.jsp").permitAll()
                    .and()
                        .exceptionHandling()
                            .accessDeniedPage("/login.jsp?authorization_error=true")
                         .accessDeniedHandler(securityConfiguration.oauthAccessDeniedHandler())
                    .and()
                        .httpBasic()
                            .authenticationEntryPoint(securityConfiguration.oAuth2AuthenticationEntryPoint())
                    .and()
                        .csrf()
                            .disable()
                        .logout()
                        .logoutUrl("/logout.do")
                        .logoutSuccessHandler(securityConfiguration.tokenLogoutSuccessHandler)
                        .logoutSuccessUrl("/login.jsp")
                    .and()
                        .formLogin()
                            .successHandler(securityConfiguration.loginSuccessDBHandler)
                            .failureHandler(securityConfiguration.authenticationFailureHandler())
                            .loginProcessingUrl("/login.do")
                            .usernameParameter("j_username")
                            .passwordParameter("j_password")
                            .failureUrl("/login.jsp?authentication_error=true")
                            .loginPage("/login.jsp")
            ;
            http.headers().frameOptions().sameOrigin();

            // @formatter:on

        }

    }
    @Configuration
    @Order(15)
    public static class SecurityConfigurationCheckToken   extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityConfiguration securityConfiguration;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                 .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                 .and()
                 .anonymous()
                .and()
                .authorizeRequests()
                    .antMatchers("/**").permitAll()
                    .antMatchers("/oauth/check_token").fullyAuthenticated()
                .and()
                    .exceptionHandling()
                    .accessDeniedHandler(securityConfiguration.oauthAccessDeniedHandler())
                .and()
                .authenticationProvider(securityConfiguration.oAuth2AuthorizationServerConfig.authenticationProvider())
                    .addFilterBefore(securityConfiguration.clientCredentialsTokenEndpointFilter(), AbstractPreAuthenticatedProcessingFilter.class)
                .httpBasic()
                    .authenticationEntryPoint(securityConfiguration.oAuth2AuthenticationEntryPoint());
            // @formatter:on
        }

    }

    @Configuration
    @Order(20)
    public static class SecurityConfigurationToken   extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityConfiguration securityConfiguration;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http
                    .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .anonymous().disable()
                    .authorizeRequests()
                        .antMatchers("/oauth/token").fullyAuthenticated()
                    .and()
                    .exceptionHandling()
                        .accessDeniedHandler(securityConfiguration.oauthAccessDeniedHandler())
                    .and()
                    .authenticationProvider(securityConfiguration.oAuth2AuthorizationServerConfig.authenticationProvider())
                        .addFilterAfter(securityConfiguration.clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
                        .httpBasic()
                        .authenticationEntryPoint(securityConfiguration.oAuth2AuthenticationEntryPoint());
            // @formatter:on
        }

    }

}

1 个答案:

答案 0 :(得分:1)

现在有效:)

我的最终代码

SecurityConfiguration:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {


    @Autowired
    private TokenLogoutSuccessHandler tokenLogoutSuccessHandler;

    @Autowired
    private AuthenticationSuccessHandler loginSuccessDBHandler; // AuthenticationSuccessHandler

    @Autowired
    private OAuth2AuthorizationServerConfig oAuth2AuthorizationServerConfig;


    @Bean
    public LoginFailureHandler authenticationFailureHandler(){
        return new LoginFailureHandler();
    }

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver(){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/WEB-INF/");
        internalResourceViewResolver.setSuffix(".jsp");
        return internalResourceViewResolver;
    }

    @Bean
    public MappingJackson2JsonView mappingJackson2JsonView(){
        MappingJackson2JsonView mappingJackson2JsonView = new MappingJackson2JsonView();
        mappingJackson2JsonView.setExtractValueFromSingleKeyModel(true);
        return mappingJackson2JsonView;
    }

    @Bean
    public ContentNegotiatingViewResolver viewResolvers(){

        ContentNegotiatingViewResolver contentNegotiatingViewResolver = new ContentNegotiatingViewResolver();

        List<ViewResolver> viewResolvers = new ArrayList<>();
        viewResolvers.add(internalResourceViewResolver());

        List<View>  listView = new ArrayList<>();
        listView.add(mappingJackson2JsonView());

        contentNegotiatingViewResolver.setViewResolvers(viewResolvers);
        contentNegotiatingViewResolver.setDefaultViews(listView);
        return contentNegotiatingViewResolver;

    }


    @Bean
    public OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPointLoginForm(){
        OAuth2AuthenticationEntryPoint clientAuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        clientAuthenticationEntryPoint.setRealmName("xaxax/client");
        clientAuthenticationEntryPoint.setTypeName(OAuth2AccessToken.BEARER_TYPE);
        return clientAuthenticationEntryPoint;
    }


    @Bean
    public OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPointCheckToken(){
        OAuth2AuthenticationEntryPoint clientAuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        clientAuthenticationEntryPoint.setRealmName("xaxax/client");
        clientAuthenticationEntryPoint.setTypeName(OAuth2AccessToken.BEARER_TYPE);
        return clientAuthenticationEntryPoint;
    }

    @Bean
    public OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPointToken(){
        OAuth2AuthenticationEntryPoint clientAuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        clientAuthenticationEntryPoint.setRealmName("xaxax/client");
        clientAuthenticationEntryPoint.setTypeName(OAuth2AccessToken.BEARER_TYPE);
        return clientAuthenticationEntryPoint;
    }


    @Bean
    public ClientDetailsUserDetailsService clientDetailsUserService(){
        ClientDetailsUserDetailsService clientDetailsUserService = new ClientDetailsUserDetailsService(this.oAuth2AuthorizationServerConfig.clientDetails());
        return clientDetailsUserService;
    }


    @Bean
    public OAuth2AccessDeniedHandler oauthAccessDeniedHandler(){
        OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler = new OAuth2AccessDeniedHandler();
        return oAuth2AccessDeniedHandler;
    }

    @Bean
    public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter(){
        ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter = new ClientCredentialsTokenEndpointFilter();

        List<AuthenticationProvider>  listAuthenticationProvider = new ArrayList<>();

        listAuthenticationProvider.add(this.oAuth2AuthorizationServerConfig.authenticationProvider());

        ProviderManager providerManager = new ProviderManager(listAuthenticationProvider);

        clientCredentialsTokenEndpointFilter.setAuthenticationManager(providerManager);

        return clientCredentialsTokenEndpointFilter;
    }

    @Configuration
    @Order(10)
    public static class SecurityConfigurationCheckToken   extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityConfiguration securityConfiguration;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http.antMatcher("/oauth/check_token")
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .anonymous()
                    .and()
                    .authorizeRequests()
                        .antMatchers("/**").permitAll()
                    .and()
                    .exceptionHandling()
                    .accessDeniedHandler(securityConfiguration.oauthAccessDeniedHandler())
                    .and()
                    .authenticationProvider(securityConfiguration.oAuth2AuthorizationServerConfig.authenticationProvider())
                    .addFilterBefore(new ApiTokenAccessFilter(securityConfiguration.oAuth2AuthorizationServerConfig.tokenServices()), AbstractPreAuthenticatedProcessingFilter.class)
                    .httpBasic()
                    .authenticationEntryPoint(securityConfiguration.oAuth2AuthenticationEntryPointCheckToken());
            // @formatter:on
        }

    }

    @Configuration
    @Order(15)
    public static class SecurityConfigurationToken   extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityConfiguration securityConfiguration;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // @formatter:off
            http.antMatcher("/oauth/token")
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .anonymous().disable()
                    .authorizeRequests()
                    .antMatchers("/oauth/token").fullyAuthenticated()
                    .and()
                    .exceptionHandling()
                    .accessDeniedHandler(securityConfiguration.oauthAccessDeniedHandler())
                    .and()
                    .authenticationProvider(securityConfiguration.oAuth2AuthorizationServerConfig.authenticationProvider())
                    .addFilterAfter(securityConfiguration.clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
                    .httpBasic()
                    .authenticationEntryPoint(securityConfiguration.oAuth2AuthenticationEntryPointToken());
            // @formatter:on
        }

    }


    @Configuration
    @Order(20)
    public static class SecurityConfigurationFrom extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityConfiguration securityConfiguration;

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

           // @formatter:off
            http
                    .sessionManagement()
                        .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
                    .and()
                        .anonymous()
                    .and()
                        .authenticationProvider(securityConfiguration.oAuth2AuthorizationServerConfig.authenticationProvider())
                        .addFilterBefore(new ApiTokenAccessFilter(securityConfiguration.oAuth2AuthorizationServerConfig.tokenServices()), AbstractPreAuthenticatedProcessingFilter.class)
                        .authorizeRequests()
                            .antMatchers("/oauth/token/**").permitAll()
                            .antMatchers("/oauth/authorize/**").permitAll()
                            .antMatchers("/oauth/principal/**").hasRole("USER")
                            .antMatchers("/login.jsp").permitAll()
                    .and()
                        .exceptionHandling()
                            .accessDeniedPage("/login.jsp?authorization_error=true")
                    .and()
                        .httpBasic()
                            .authenticationEntryPoint(securityConfiguration.oAuth2AuthenticationEntryPointLoginForm())
                    .and()
                        .csrf()
                            .disable()
                        .logout()
                        .logoutUrl("/logout.do")
                        .logoutSuccessHandler(securityConfiguration.tokenLogoutSuccessHandler)
                        .logoutSuccessUrl("/login.jsp")
                    .and()
                        .formLogin()
                            .successHandler(securityConfiguration.loginSuccessDBHandler)
                            .failureHandler(securityConfiguration.authenticationFailureHandler())
                            .loginProcessingUrl("/login.do")
                            .usernameParameter("j_username")
                            .passwordParameter("j_password")
                            .failureUrl("/login.jsp?authentication_error=true")
                            .loginPage("/login.jsp")
            ;
            http.headers().frameOptions().sameOrigin();
            // @formatter:on

        }

    }


}

OAuth2AuthorizationServerConfig:

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsServiceImpl;

    @Autowired
    private DataSource dataSource;


    @Bean
    public ClientDetailsService clientDetails (){
        JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(this.dataSource);
        return jdbcClientDetailsService;
    }

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


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(this.userDetailsServiceImpl);
        daoAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
        return daoAuthenticationProvider;
    }

    @Bean
    public EmptyPasswordEncoder emptyPasswordEncoder(){
        return new EmptyPasswordEncoder();
    }


    @Bean
    public AuthenticationProvider noPasswordAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setUserDetailsService(this.userDetailsServiceImpl);
        daoAuthenticationProvider.setPasswordEncoder(this.emptyPasswordEncoder());
        return daoAuthenticationProvider;
    }



    @Bean
    public DefaultOAuth2RequestFactory oAuth2RequestFactory(){

        DefaultOAuth2RequestFactory oAuth2RequestFactory = new DefaultOAuth2RequestFactory(this.clientDetails());
        return oAuth2RequestFactory;

    }



    @Bean
    public UserApprovalHandler userApprovalHandler(){
        UserApprovalHandler userApprovalHandler = new UserApprovalHandler();
        userApprovalHandler.setTokenStore(this.tokenStore());
        userApprovalHandler.setRequestFactory(this.oAuth2RequestFactory());
        return userApprovalHandler;
    }


    @Bean
    public DefaultTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(this.tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setClientDetailsService(this.clientDetails());
        return tokenServices;
    }

    @Bean
    public CheckTokenEndpoint checkTokenEndpoint(){
        CheckTokenEndpoint checkTokenEndpoint = new CheckTokenEndpoint();
        checkTokenEndpoint.setTokenServices(this.tokenServices());
        return checkTokenEndpoint;
    }



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

        clients.inMemory().withClient("xaxax");
        clients.withClientDetails(this.clientDetails());

    }



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

        List<AuthenticationProvider>  listAuthenticationProvider = new ArrayList<>();

        listAuthenticationProvider.add(this.authenticationProvider());

        ProviderManager providerManager = new ProviderManager(listAuthenticationProvider);

        endpoints
                .tokenStore(this.tokenStore())
                .tokenServices(tokenServices())
                .userApprovalHandler(userApprovalHandler())
                .authenticationManager(providerManager)
                .setClientDetailsService(clientDetails());

    }

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

        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();


    }


}

ApiTokenAccessFilter:

public class ApiTokenAccessFilter extends OAuth2AuthenticationProcessingFilter {

    public ApiTokenAccessFilter(ResourceServerTokenServices resourceServerTokenServices) {

        super();
        setStateless(false);
        setAuthenticationManager(oauthAuthenticationManager(resourceServerTokenServices));
    }

    private AuthenticationManager oauthAuthenticationManager(ResourceServerTokenServices tokenServices) {

        OAuth2AuthenticationManager oauthAuthenticationManager = new OAuth2AuthenticationManager();

        oauthAuthenticationManager.setResourceId("oauth2-resource");
        oauthAuthenticationManager.setTokenServices(tokenServices);
        oauthAuthenticationManager.setClientDetailsService(null);

        return oauthAuthenticationManager;
    }
}

帮助我的链接:

Spring Security OAuth2 - @EnableOauth2Sso but accept tokens as authentication, too

http://www.baeldung.com/spring-security-multiple-entry-points

相关问题