溫馨提示×

SpringBoot怎么實現(xiàn)安全認(rèn)證和授權(quán)

小億
97
2024-04-18 15:05:16
欄目: 編程語言

Spring Boot提供了Spring Security來實現(xiàn)安全認(rèn)證和授權(quán)功能。下面是一個簡單的示例來演示如何在Spring Boot中實現(xiàn)基本的安全認(rèn)證和授權(quán):

  1. 添加依賴:在pom.xml文件中添加Spring Security的依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. 創(chuàng)建一個WebSecurityConfig類來配置安全規(guī)則:
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/user/**").hasRole("USER")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
    }
}
  1. 創(chuàng)建一個UserDetailsService實現(xiàn)類來獲取用戶信息:
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if ("admin".equals(username)) {
            return User.withDefaultPasswordEncoder().username("admin").password("admin").roles("ADMIN").build();
        } else if ("user".equals(username)) {
            return User.withDefaultPasswordEncoder().username("user").password("user").roles("USER").build();
        } else {
            throw new UsernameNotFoundException("User not found");
        }
    }
}
  1. 創(chuàng)建一個Controller來測試安全認(rèn)證和授權(quán):
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/admin/test")
    public String adminTest() {
        return "Admin test";
    }

    @GetMapping("/user/test")
    public String userTest() {
        return "User test";
    }
}

這樣就可以在Spring Boot中實現(xiàn)基本的安全認(rèn)證和授權(quán)功能了。當(dāng)訪問/admin/test時需要ADMIN角色才能訪問,訪問/user/test時需要USER角色才能訪問??梢酝ㄟ^配置WebSecurityConfig類來定義更復(fù)雜的安全規(guī)則和用戶信息獲取方式。

0