原文: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";
}

最新文章

  1. 跨越语言的障碍:C++/CLI 调用 C#
  2. MYSQL基础知识总结
  3. android的listview的详细用法
  4. HDU 4865 Peter&#39;s Hobby --概率DP
  5. C#解压、压缩RAR文件
  6. XCODE 代码行统计
  7. 03 持续集成和部署/基础设施 - DevOps之路
  8. .NET开发微信小程序-Template模块开发
  9. C#List&lt;object&gt;排序
  10. AppiumLibrary常用关键字
  11. python 计算机发展史,线程Process使用 for循环创建 2种传参方式 jion方法 __main__的解释
  12. matlab之导入txt文件并取其中一列数据
  13. mysql之行(记录)的详细操作
  14. 数据库中DQL、DML、DDL、DCL的概念与区别
  15. Jquery获取radio单选按钮的value与后面的文字
  16. CF 914G Sum the Fibonacci——子集卷积
  17. lintcode-473-单词的添加与查找
  18. 打开wamp中的phpmyadmin出现403的错误
  19. 关于props的注意事项!
  20. python格式化输出的方式汇总

热门文章

  1. a标签设置水平右对齐
  2. 基于GPU的算法并行化
  3. React-native 导航插件React Navigation 4.x的使用
  4. 【操作系统之八】Linux常用命令之top
  5. CentOS7 CPU 降频问题
  6. Shell脚本之三 传递参数
  7. 【C学习笔记】一
  8. C/C++ 指针常量和常量指针
  9. Debian 9 / Debian 10 / Ubuntu 18.04 / Ubuntu 18.10快速开启BBR加速 或 关闭BBR加速
  10. IDEA 环境下更改Maven的仓库镜像提高下载速度