Spring Cloud注册中心Eureka设置访问权限并自定义鉴权页面

使用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/

进行以上操作后,会出现服务不能注册的问题,此问题请阅读下我的另外一篇博客【踩坑】Spring Cloud集成Spring Security后服务在注册中心不能注册

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";
}

搞定 ?

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值