原文:https://blog.csdn.net/a823007573/article/details/88971496
使用Spring Security实现鉴权
1. 导入Spring Security的jar包。
<!--spring security--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2. 在配置文件中添加Spring Security相关配置
spring: security: # 开启认证,Spring Cloud2.0后添加jar会自动集成并开启 # basic.enabled: true # 用户名密码 user: name: test password: test
并修改eureka的注册中心地址,http://用户名:密码@主机:端口/eureka/ # 注册中心地址 serviceUrl.defaultZone: http://${security.user.name}:${spring.security.user.password}@${spring.eureka.instance.hostname}:${server.port}/eureka/
每个eureka client端都要修改serviceUrl.defaultZone的地址,加上用户名密码,不然客户端都连不上eureka server了。
3. 自定义Spring Security的鉴权页面
首先准备好自定义的页面,并使用spring boot推荐的thymeleaf进行HTML页面的管理。
导包:
<!--thymeleaf模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
添加一下thymeleaf配置:
#外一层为spring: thymeleaf: # 指定模板位置 prefix: classpath:/views/ mode: HTML5
通过继承WebSecurityConfigurerAdapter来进行自定义页面的配置:
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()//对请求进行鉴权 .antMatchers("/login")//登录页面不鉴权 .permitAll(); http.formLogin() .loginPage("/login")//登录页面 .failureUrl("/login?error")//鉴权失败的页面 .permitAll(); http.csrf().disable(); super.configure(http); } }
添加登录控制器用于跳转到登录页面:
/** * 跳转到登录页 * @return */ @GetMapping("/login") public String toLogin(String error, Model model) { //利用error来判断是否登录出错,实质上没有值,对应设置的failureUrl if (error != null) { model.addAttribute("errMsg", "用户名或密码错误!"); } return "/login"; }