Spring Cloud注册中心Eureka设置访问权限并自定义鉴权页面
2024-08-29 01:28:06
原文: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";
}
最新文章
- 跨越语言的障碍:C++/CLI 调用 C#
- MYSQL基础知识总结
- android的listview的详细用法
- HDU 4865 Peter&#39;s Hobby --概率DP
- C#解压、压缩RAR文件
- XCODE 代码行统计
- 03 持续集成和部署/基础设施 - DevOps之路
- .NET开发微信小程序-Template模块开发
- C#List<;object>;排序
- AppiumLibrary常用关键字
- python 计算机发展史,线程Process使用 for循环创建 2种传参方式 jion方法 __main__的解释
- matlab之导入txt文件并取其中一列数据
- mysql之行(记录)的详细操作
- 数据库中DQL、DML、DDL、DCL的概念与区别
- Jquery获取radio单选按钮的value与后面的文字
- CF 914G Sum the Fibonacci——子集卷积
- lintcode-473-单词的添加与查找
- 打开wamp中的phpmyadmin出现403的错误
- 关于props的注意事项!
- python格式化输出的方式汇总