package com.leimingtech.sso;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.tomcat.util.http.parser.Authorization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
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;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
/**
* Created by yun on 2017/7/27.
*/
public class Config {
public static final String OAUTH_CLIENT_ID = "oauth_client";
public static final String OAUTH_CLIENT_SECRET = "oauth_client_secret";
public static final String RESOURCE_ID = "my_resource_id";
public static final String[] SCOPES = { "read", "write" };
// private static BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Bean
@ConfigurationProperties("spring.datasource")
public static HikariDataSource dataSource() {
return (HikariDataSource) DataSourceBuilder.create()
.type(HikariDataSource.class).build();
}
@Configuration
@EnableAuthorizationServer
static class OAuthAuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Resource(name = "oldPasswordEncoder")
private OldPasswordEncoder passwordEncoderOld;
@Autowired
private AuthorizationEndpoint authorizationEndpoint;
@PostConstruct
public void init() {
// authorizationEndpoint.setUserApprovalPage("forward:/oauth/my_approval_page");
// authorizationEndpoint.setErrorPage("forward:/oauth/my_error_page");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource())
.withClient(OAUTH_CLIENT_ID)
.secret(OAUTH_CLIENT_SECRET)
.resourceIds(RESOURCE_ID)
.scopes(SCOPES)
.authorities("ROLE_USER")
.authorizedGrantTypes("authorization_code", "refresh_token")
.redirectUris("http://default-oauth-callback.com")
.accessTokenValiditySeconds(60*30) // 30min
.refreshTokenValiditySeconds(60*60*24); // 24h
}
@Bean
public ApprovalStore approvalStore() {
return new JdbcApprovalStore(dataSource());
}
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource());
}
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
security.passwordEncoder(passwordEncoderOld)/*.tokenKeyAccess().checkTokenAccess()*/;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.approvalStore(approvalStore()) // oauth_approvals
.authorizationCodeServices(authorizationCodeServices()) // oauth_code
.tokenStore(tokenStore())/*.userDetailsService()*/
/*.authenticationManager()*/
/*.tokenGranter()*/
/*.requestFactory()*/; // oauth_access_token & oauth_refresh_token
}
}
@Configuration
@EnableResourceServer
static class OAuthResourceConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.antMatcher("/oauth/**")
.authorizeRequests()
.antMatchers("/oauth/index").permitAll()
.antMatchers("/oauth/token").permitAll()
.antMatchers("/oauth/check_token").permitAll()
.antMatchers("/oauth/confirm_access").permitAll()
.antMatchers("/oauth/error").permitAll()
.antMatchers("/oauth/my_approval_page").permitAll()
.antMatchers("/oauth/my_error_page").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/oauth/index")
.loginProcessingUrl("/oauth/login");
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").access("#oauth2.hasScope('read')")
.antMatchers(HttpMethod.POST, "/api/**").access("#oauth2.hasScope('write')");
}
}
@Configuration
@EnableWebSecurity
static class SecurityConfig extends WebSecurityConfigurerAdapter {
@Resource(name = "customAuthenticationProvider")
private CustomAuthenticationProvider authenticationProvider;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/oauth/authorize").authenticated()
.and()
.httpBasic().realmName("OAuth Server");
}
@Override