引入spring security oauth

parent 6ebc95d2
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>gic-pom-base</artifactId>
<groupId>com.gic</groupId>
<version>4.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gic-demo-single-api</artifactId>
<version>${libraryVersion}</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<libraryVersion>1.0-SNAPSHOT</libraryVersion>
</properties>
<dependencies>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-base-api</artifactId>
<version>${gic-base-api}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<flattenMode>defaults</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>gic-pom-base</artifactId>
<groupId>com.gic</groupId>
<version>4.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>gic-demo-single-api</artifactId>
<version>${libraryVersion}</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<libraryVersion>1.0-SNAPSHOT</libraryVersion>
</properties>
<dependencies>
<dependency>
<groupId>com.gic</groupId>
<artifactId>gic-base-api</artifactId>
<version>${gic-base-api}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>${project.build.sourceEncoding}</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>1.1.0</version>
<configuration>
<flattenMode>defaults</flattenMode>
</configuration>
<executions>
<!-- enable flattening -->
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<!-- ensure proper cleanup -->
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.gic.demo.single.web;
import com.gic.dubbo.util.DubboContextUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ImportResource;
/**
* Spring Boot Web 启动类
*
* @author zhurz
*/
@SpringBootApplication
@ImportResource(value = {
"classpath*:applicationContext-init.xml",
"classpath*:dubbo-setting.xml",
"classpath*:dubbo-gic-demo-web.xml",
"classpath*:spring-interceptor.xml"
})
public class Main {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Main.class, args);
DubboContextUtil.setApplicationContext(context);
}
package com.gic.demo.single.web;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import com.gic.dubbo.util.DubboContextUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ImportResource;
/**
* Spring Boot Web 启动类
*
* @author zhurz
*/
@EnableApolloConfig({ "COMMON.redis" })
@ImportResource(value = {
"classpath*:applicationContext-init.xml",
"classpath*:dubbo-setting.xml",
"classpath*:dubbo-gic-demo-web.xml",
"classpath*:spring-interceptor.xml"
})
@SpringBootApplication(scanBasePackages = { "com.gic.demo.*" })
public class Main {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Main.class, args);
DubboContextUtil.setApplicationContext(context);
}
}
\ No newline at end of file
package com.gic.demo.single.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 1800, redisNamespace = "gic_demo")
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
@Bean
public static ConfigureRedisAction configureRedisAction() {
return ConfigureRedisAction.NO_OP;
}
}
package com.gic.demo.single.web;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.filter.HttpPutFormContentFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public HttpPutFormContentFilter httpPutFormContentFilter() {
return new HttpPutFormContentFilter();
}
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}
/**
*
*/
package com.gic.demo.single.web.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.data.redis.RedisOperationsSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.cors.CorsUtils;
import com.gic.authcenter.security.core.authc.AuthcenterCookieClearingLogoutHandler;
import com.gic.authcenter.security.core.authc.AuthcenterLoginUrlAuthenticationEntryPoint;
import com.gic.authcenter.security.core.authc.AuthcenterLogoutSuccessHandler;
import com.gic.authcenter.security.core.authc.AuthcenterRedisSessionClearingLogoutHandler;
import com.gic.authcenter.security.core.authz.AuthcenterAccessDeniedHandler;
import com.gic.authcenter.security.core.authz.AuthcenterPermissionEvaluator;
import com.gic.demo.single.web.security.handler.CustomAuthenticationSuccessHandler;
/**
*
* @author leeon
*
*/
@Configuration
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private ServerProperties serverProperties;
@Autowired
private RedisOperationsSessionRepository redisOperationsSessionRepository;
@Bean
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringSessionBackedSessionRegistry sessionRegistry() {
return new SpringSessionBackedSessionRegistry(((FindByIndexNameSessionRepository) redisOperationsSessionRepository));
}
@Bean
public RequestContextListener requestContextListener() {
return new RequestContextListener();
}
@Bean
public CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler() {
return new CustomAuthenticationSuccessHandler();
}
@Bean
public AuthcenterAccessDeniedHandler authcenterAccessDeniedHandler() {
return new AuthcenterAccessDeniedHandler();
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.antMatchers("/","/login")
.permitAll()
.requestMatchers(CorsUtils::isPreFlightRequest)
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.successHandler(customAuthenticationSuccessHandler())
.and()
.logout()
.addLogoutHandler(new AuthcenterCookieClearingLogoutHandler(
serverProperties.getServlet().getSession().getCookie().getName()))
.addLogoutHandler(new AuthcenterRedisSessionClearingLogoutHandler(redisOperationsSessionRepository))
.addLogoutHandler(new SecurityContextLogoutHandler())
.logoutSuccessHandler(new AuthcenterLogoutSuccessHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(authcenterAccessDeniedHandler())
.authenticationEntryPoint(new AuthcenterLoginUrlAuthenticationEntryPoint("/login"))
.and()
.sessionManagement()
.maximumSessions(1)
.sessionRegistry(sessionRegistry())
.and()
.and().csrf().disable()
;
// @formatter:on
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Bean
public AuthcenterPermissionEvaluator authcenterPermissionEvaluator() {
return new AuthcenterPermissionEvaluator();
}
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(authcenterPermissionEvaluator());
return expressionHandler;
}
}
}
package com.gic.demo.single.web.security.handler;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.core.Authentication;
import com.gic.authcenter.security.core.authc.AuthcenterAuthenticationSuccessHandler;
/**
* 认证成功
*
* @author leeon
*
*/
public class CustomAuthenticationSuccessHandler extends AuthcenterAuthenticationSuccessHandler {
Logger logger = LogManager.getLogger(getClass());
@Autowired
private Environment environment;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
super.onAuthenticationSuccess(request, response, authentication, environment);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gic</groupId>
<artifactId>gic-demo-single</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>gic-demo-single-api</module>
<module>gic-demo-single-service</module>
<module>gic-demo-single-web</module>
</modules>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gic</groupId>
<artifactId>gic-demo-single</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>gic-demo-single-api</module>
<module>gic-demo-single-service</module>
<module>gic-demo-single-web</module>
</modules>
</project>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment