zoukankan      html  css  js  c++  java
  • Spring Cloud注册中心Eureka设置访问权限并自定义鉴权页面

    原文: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";
    } 
  • 相关阅读:
    IOS Date, NSDateFormatter, compare, dateFromString:mydatestr
    IOS Retain,nil,alloc,init
    IOS NSArray,NSDictionary
    object c基础, 基本类型(NSString,char*NSDate,NSData),集合NSArray,NSMutableArray,NSDictionary,NSMutableDictionary,NSSet,NSMutableSet
    IOS UIProgressView 用法
    UIButton 用法
    XCode 快捷键,MAC 快捷键
    苹果软件系列产品介绍
    android 之多线程应用[message,messagequeue,handler,looper,asynchtask]
    Linux查看程序被哪个端口占用
  • 原文地址:https://www.cnblogs.com/shihaiming/p/11416265.html
Copyright © 2011-2022 走看看