一、maven引用
<!--使用它之后项目必须增加一个bootstrap.yml文件进行配置-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<artifactId>spring-cloud-config-refresh-starter</artifactId>
<groupId>com.gwm.cloud</groupId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
二、配置账号和密码:
spring:
security:
user:
name: "admin"
password: "admin"
三、配置SecurityFilterChain(WebMvc模式)
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableMethodSecurity
public class WebMvcSecurityConfiguration {
private static final Logger LOGGER = Logger.getGlobal();
private static final RequestHeaderRequestMatcher X_REQUESTED_WITH = new RequestHeaderRequestMatcher(
"X-Requested-With", "XMLHttpRequest");
private final ApplicationContext applicationContext;
private final SecurityProperties security;
public WebMvcSecurityConfiguration(ApplicationContext applicationContext, SecurityProperties security) {
this.applicationContext = applicationContext;
this.security = security;
}
/**
* http请求路径权限与过滤链配置
* @param http
* @return
*/
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
LOGGER.info("配置中心用户信息:" + this.security.getUser().getName());
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests
.requestMatchers(new AntPathRequestMatcher("/actuator/**"),
new AntPathRequestMatcher("/eureka/**"),
new AntPathRequestMatcher("/login"))
.permitAll()
.dispatcherTypeMatchers(DispatcherType.ASYNC)
.permitAll()
.anyRequest()
.authenticated())
.formLogin(AbstractHttpConfigurer::disable)
.logout(AbstractHttpConfigurer::disable)
.httpBasic(Customizer.withDefaults())
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> {
// 匹配逻辑
LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> entryPoints = new LinkedHashMap<>();
entryPoints.put(X_REQUESTED_WITH, new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
// 返回浏览器自带的basic认证
DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(entryPoints);
entryPoint.setDefaultEntryPoint(new BasicAuthenticationEntryPoint());
httpSecurityExceptionHandlingConfigurer.authenticationEntryPoint(entryPoint);
});
http.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
.ignoringRequestMatchers(new AntPathRequestMatcher("/**")));
return http.build();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。