原创 spring boot oauth2 集成(WebSecurity+AuthorizationServer+ResourceServer)

分类:2018-03-31 21:15:30   177人阅读  评论   分享

spring oauth2和WebSecurity集成坑太多,留个笔记,以示后人...

PS:这个配置查了一天,酱油君也是醉了

交流请加页脚q群

对你有用,点击捐囎,求打赏

package com.auth2Server;

import com.auth2Server.config.AuthServerProperties;
import com.auth2Server.config.OAuth2FeignRequestInterceptor;
import com.auth2Server.model.entities.AppClientDetails;
import com.auth2Server.repository.AppRepository;
import com.auth2Server.sec.AjaxAuthFailHandler;
import com.auth2Server.sec.AjaxAuthSuccessHandler;
import com.auth2Server.sec.UnauthorizedEntryPoint;
import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.authserver.AuthorizationServerProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
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.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.*;
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.ClientRegistrationException;

/**
 * @author Damon
 * @create 2018-02-16 18:19
 **/
@EnableOAuth2Client

@SpringBootApplication
@Slf4j
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableConfigurationProperties({ AuthServerProperties.class })
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }


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


    @Configuration
    @EnableAuthorizationServer
    @EnableConfigurationProperties(AuthorizationServerProperties.class)
    static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {


/*        @Autowired
          ClientDetailsService clientDetailsService;*/

        @Autowired
        AppRepository appRepository;

        @Autowired
        private AuthenticationManager authenticationManager;

        @Bean
        ClientDetailsService getClientDetailsService(){
            return clientId -> appRepository.findByAppId(clientId)
                    .map(AppClientDetails::new)
                    .orElseThrow(() -> new ClientRegistrationException("The given client is invalid " + clientId));
        }


        @Override
        public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            oauthServer.tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()").allowFormAuthenticationForClients();
        }
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.withClientDetails(getClientDetailsService());
        }

        @Override
        public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.authenticationManager(authenticationManager);

        }
    }



    @Configuration
    @EnableResourceServer
    @Order(6)
    static class OAuth2ResourceConfig extends ResourceServerConfigurerAdapter {

        @Bean
        @ConfigurationProperties(prefix = "security.oauth2.client")
        public ClientCredentialsResourceDetails clientCredentialsResourceDetails() {
            return new ClientCredentialsResourceDetails();
        }

        @Bean
        public RequestInterceptor oauth2FeignRequestInterceptor() {
            return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), clientCredentialsResourceDetails());
        }

        @Bean
        public OAuth2RestTemplate clientCredentialsRestTemplate() {
            return new OAuth2RestTemplate(clientCredentialsResourceDetails());
        }

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

            http.requestMatchers().antMatchers("/api/**")
                    .and()
                    .authorizeRequests()
                    .antMatchers("/api/**")
                    .authenticated()
                    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        }
    }


    @Configuration
    @EnableWebSecurity
    @Order(20)
    static class webConfig extends WebSecurityConfigurerAdapter {


        @Autowired
        private UserDetailsService userDetailsService;

        private static final String[] AUTH_WHITELIST = {
                "/swagger-resources/**",
                "/swagger-ui.html",
                "/v2/api-docs",
                "/webjars/**",
                "/upload/**"
        };

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/style/**");
            web.ignoring().antMatchers("/kaptcha/**");
            web.ignoring().antMatchers("/payment/alipayNotify/**");
            web.ignoring().antMatchers(AUTH_WHITELIST);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception{
            http
                    .authorizeRequests()
                   .anyRequest()
                    .authenticated()
                    .and()
                    .userDetailsService(userDetailsService)
                    .formLogin()
                    .successHandler(new AjaxAuthSuccessHandler())
                    .failureHandler(new AjaxAuthFailHandler())
                    .loginPage("/login").defaultSuccessUrl("/home").permitAll()
                    .and()
                    .exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint())
                    .and()
                    .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
                    .and().csrf().disable();
        }

    }
}


引用:

https://segmentfault.com/a/1190000012260914

https://blog.csdn.net/buyaore_wo/article/details/48680981

https://blog.csdn.net/huhanguang89/article/details/62045095

分享到: