springsecurity整合springboot實現自定義登錄頁面及訪問路徑權限配置


springsecurity整合springboot實現自定義登錄頁面及訪問路徑權限配置

編寫配置類繼承WebSecurityConfigurerAdapter,重寫void configure(HttpSecurity http)方法

package com.yl.config;

import com.yl.service.impl.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * spring security配置類
 *
 * @author Y-wee
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 登錄表單配置
        http.formLogin()
                // 設置登錄頁面
                .loginPage("/login.html")
                /**
                 * 設置登錄請求路徑(自定義),登錄頁面的登錄請求路徑必須跟這里保持一致
                 * 該請求實現邏輯不需要我們自己寫,我們只需要配置好路徑即可,邏輯spring security會幫我們處理
                 */
                .loginProcessingUrl("/user/login")
                // 設置登錄成功之后跳轉的路徑,permitAll()表示任何角色都可以訪問
                .defaultSuccessUrl("/index.html").permitAll()
                // 認證配置
                .and().authorizeRequests()
                // 設置路徑不需要認證即可訪問,注意登錄請求路徑配置在這里
                .antMatchers("/", "/login/noLogin", "/user/login").permitAll()
                /**
                 * 設置路徑只有admin角色可以訪問,與hasRole()方法類似,不同之處:
                 * hasRole()默認會給角色加上ROLE_前綴(可點進方法查看源碼驗證)
                 */
                .antMatchers("/login/admin").hasAuthority("admin")
                // 設置路徑admin和normal角色都可以訪問
                .antMatchers("/login/normal").hasAnyAuthority("admin", "normal")
                /**
                 * 設置任何尚未匹配的URL只需要經過認證就可以訪問
                 * 注意:anyRequest()只能配置在antMatchers()后面
                 * 自定義登錄頁面后如果沒有anyRequest()的相關配置,則任何尚未匹配的url不經過認證(登錄)也可以訪問
                 */
                .anyRequest().authenticated()
                // 設置任何尚未匹配的URL都將被拒絕訪問
//                .anyRequest().denyAll()
                // 關閉csrf防護
                .and().csrf().disable();

        // 設置403(沒有權限)跳轉頁面
        http.exceptionHandling().accessDeniedPage("/403.html");

        // 注銷配置
        http.logout()
                // 設置注銷url
                .logoutUrl("/logout")
                // 設置注銷成功要跳轉的url
                .logoutSuccessUrl("/login.html");
    }
}

中文文檔解釋:

中文文檔地址:https://www.springcloud.cc/spring-security.html#jc-form

注意:登錄表單的用戶名和密碼屬性默認必須為username和password,如果要自定義則加上如下配置:

http.formLogin()
    .usernameParameter("用戶名參數名")
    .passwordParameter("密碼參數名");

基於注解實現訪問路徑角色權限控制

在配置類或者啟動類開啟注解功能

// 啟用@Secured\@PreAuthorize\@PostAuthorize注解
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {}

在controller加注解進行角色權限控制

@GetMapping("/update1")
// 用戶必須具有ROLE_update角色才能訪問該路徑,@Secured注解判斷的角色必須以ROLE_前綴修飾
@Secured("ROLE_update")
public String update1(){
    return "welcome to update";
}

@GetMapping("/update2")
@PreAuthorize("hasAnyAuthority('update')")
public String update2(){
    return "welcome to update";
}

@GetMapping("/update3")
@PostAuthorize("hasAnyRole('update')")
public String update3(){
    return "welcome to update";
}

@PostAuthorize和@Secured的作用應該一看就懂,不作過多解釋,其區別跟配置類里面寫的一樣

具體解釋可參考官網:https://docs.spring.io/spring-security/site/docs/5.3.4.RELEASE/reference/html5/#el-access


免責聲明!

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



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