构建安全且高效的Spring Cloud单点登录系统
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableDiscoveryClient
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // 禁用CSRF保护
.authorizeRequests()
.antMatchers("/login").permitAll() // 允许登录接口无授权访问
.anyRequest().authenticated() // 其他所有请求需要身份验证
.and()
.logout()
.logoutUrl("/logout") // 指定注销URL
.clearAuthentication(true) // 注销时清除认证信息
.invalidateHttpSession(true) // 注销时使HTTP会话失效
.deleteCookies("JSESSIONID") // 注销时删除JSESSIONID cookie
.logoutSuccessUrl("/login"); // 注销成功后跳转到登录页面
}
}
这段代码演示了如何在Spring Cloud环境中使用Spring Security来保护应用程序的安全性。它禁用了CSRF保护,允许对登录接口的无授权访问,并且配置了注销功能。这样的安全配置可以有效地防止未授权的访问,增强应用程序的安全性。
评论已关闭