iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 28
0
Modern Web

站在Web前端人員角度,學習 Spring Boot 後端開發系列 第 28

Day 28 - Spring Boot Security 守護安全

  • 分享至 

  • twitterImage
  •  

Spring Security

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

spring security 架構
spring security 在web應用中是基於filter的,可以擁有身份驗證與訪問控制的實作(可以想像它是一個實作套件),有安全管理的機制與預設GUI驗證畫面與機制。

https://ithelp.ithome.com.tw/upload/images/20201007/20118857eZj6hox1M2.png

Maven配置

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>sprixmng-boot-starter-security</artifactId>
</dependency>

預設訪問每個端點時,會先導到spring security預設的登入頁。

https://ithelp.ithome.com.tw/upload/images/20201007/20118857lmjMYGaVYW.png

登入錯誤會顯示
https://ithelp.ithome.com.tw/upload/images/20201007/201188579nXqLGCGeT.png

Spring Security 設定檔

新增一個WebSecurityConfig.java 檔案繼承WebSecurityConfigurerAdapter來設定,

覆寫configure() 的方法設置http security 的參數

@Configuration
@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests() // 定義哪些url需要被保護
            .antMatchers("/").permitAll()  // 定義匹配到"/" 不需要驗證
            .antMatchers("/swagger-ui.html").permitAll() // 匹配到"/swagger-ui.html", 不需要身份驗證
            .anyRequest().authenticated() // 其他尚未匹配到的url都需要身份驗證
            .and()
            .formLogin()
            .and()
            .httpBasic();
    }
}

現在嘗試要設定一些角色,先不考慮將角色放置資料庫中,先利用內存來使用

角色ADMIN 可以訪問/demo/user 與 /demo/admin

角色USER 只可以訪問/demo/user

@Configuration
@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        // 設置角色定義
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password("123456")
                .roles("ADMIN", "USER") // 擁有ADMIN 與 USER角色
                .and()
                .withUser("user")
                .password("123")
                .roles("USER");// 擁有USER角色
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests() // 定義哪些url需要被保護
                .antMatchers("/user").hasRole("USER")// 定義匹配到"/user"底下的需要有USER的這個角色才能進去
                .antMatchers("/admin").hasRole("ADMIN") // 定義匹配到"/admin"底下的需要有ADMIN的這個角色才能進去
                .anyRequest().authenticated() // 其他尚未匹配到的url都需要身份驗證
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }

上一篇
Day 27 - Spring Boot @ManyToMany多對多查詢
下一篇
Day 29 - Spring Boot 想要資料令牌要先帶來!- JWT
系列文
站在Web前端人員角度,學習 Spring Boot 後端開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言