springboot2集成oauth2

最近拿oauth2练手,搭了oauth2的demo。

服务端配置


/**
 * oauth2配置
 * @author hao
 * @Date 2018-04-19
 */
public class OAuth2ServerConfig {

	/**
	 * oauth2资源服务器配置
	 * @author kdlq-hao
	 */
    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    	
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
	            .requestMatchers()
	        	.antMatchers("/auth/**", "/user/me")// 由oauth2拦截检验,根据token验证登录
	        	.and()
                .authorizeRequests()
                .antMatchers("/auth/**")// /auth路径的资源需要token
                .authenticated();
        }
    }


	/**
	 * oauth2授权服务器配置
	 * @author kdlq-hao
	 */
    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        AuthenticationManager authenticationManager;

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

            String finalSecret = new BCryptPasswordEncoder().encode("123456");
            // 创建两个客户端,client_1使用授权码模式,client_2使用密码模式
            clients.inMemory()
            		.withClient("client_1")
            		.authorizedGrantTypes("authorization_code", "refresh_token", "implicit")
            		.scopes("get_user_info")
            		.secret(finalSecret)
            		.autoApprove(true)
            		.and()
            		.withClient("client_2")
                    .authorizedGrantTypes("password", "refresh_token")
                    .scopes("get_user_info")
                    .secret(finalSecret);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
            endpoints
                    .tokenStore(new InMemoryTokenStore())
                    .authenticationManager(authenticationManager);
        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
            //允许表单认证
            oauthServer.allowFormAuthenticationForClients();
        }

    }
}

注意:

1,clientdetails继承userdtails,如果client时如果验证失败,会进入userdetailsservice验证,要注意密码encode。

2,由resourceserver拦截的请求才会进行token权限验证。

3,配置sessionId,避免session冲突。server.servlet.session.cookie.name: AUTH_SESSION

4,拦截后登陆页面一定要form表单提交才能重定向

客户端配置:


@SpringBootApplication
@RestController
@EnableOAuth2Client
public class Oauth2clientApplication extends WebSecurityConfigurerAdapter {

	@Autowired
	OAuth2ClientContext oauth2ClientContext;

	@RequestMapping("/user")
	public Principal user(Principal principal) {
		return principal;
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.antMatcher("/**").authorizeRequests()
				.antMatchers("/", "/login**", "/webjars/**", "/error**").permitAll()
				.anyRequest().authenticated()
				.and()
				.exceptionHandling()
				.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
				.logoutSuccessUrl("/").permitAll()
				.and()
				.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
				.and()
				.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
	}

	public static void main(String[] args) {
		SpringApplication.run(Oauth2clientApplication.class, args);
	}

	@Bean
	public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(filter);
		registration.setOrder(-100);
		return registration;
	}

	private Filter ssoFilter() {
		OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
				"/login/facebook");
		OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
		facebookFilter.setRestTemplate(facebookTemplate);
		UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
				facebook().getClientId());
		tokenServices.setRestTemplate(facebookTemplate);
		facebookFilter.setTokenServices(tokenServices);
		return facebookFilter;
	}

	@Bean
	@ConfigurationProperties("security.oauth2.client")
	public AuthorizationCodeResourceDetails facebook() {
		return new AuthorizationCodeResourceDetails();
	}
	@Bean
	@ConfigurationProperties("security.oauth2.resource")
	public ResourceServerProperties facebookResource() {
		return new ResourceServerProperties();
	}

}

客户端配置主要参考官方TUTORIAL。把oauth2client拦截器置前实现拦截请求,授权后自动重定向。

git地址:https://gitee.com/StupidRobot/oauth2.git

你可能感兴趣的:(springboot2集成oauth2)