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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM