溫馨提示×

如何在Java API中實(shí)現(xiàn)身份驗(yàn)證和授權(quán)

小樊
95
2024-08-09 17:38:42
欄目: 編程語言

在Java中實(shí)現(xiàn)身份驗(yàn)證和授權(quán)可以使用一些現(xiàn)成的框架和工具,比如Spring Security。Spring Security是一個功能強(qiáng)大且靈活的框架,可以幫助我們實(shí)現(xiàn)用戶身份驗(yàn)證和授權(quán)。

以下是一個簡單的示例,演示如何在Java API中使用Spring Security進(jìn)行身份驗(yàn)證和授權(quán):

  1. 添加Spring Security依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. 創(chuàng)建一個Security配置類:
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 SecurityConfig extends WebSecurityConfigurerAdapter {
    
}
  1. 配置用戶和權(quán)限:
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig 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)建一個用戶和角色:
import org.springframework.context.annotation.Bean;
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.security.core.userdetails.UserDetailsService;
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.withUsername("admin").password("{noop}admin").roles("ADMIN").build();
        } else if ("user".equals(username)) {
            return User.withUsername("user").password("{noop}user").roles("USER").build();
        }
        throw new UsernameNotFoundException("User not found");
    }
}
  1. 在控制器中添加注解進(jìn)行授權(quán)驗(yàn)證:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExampleController {

    @GetMapping("/admin")
    public String admin() {
        return "Welcome Admin!";
    }

    @GetMapping("/user")
    public String user() {
        return "Welcome User!";
    }

    @GetMapping("/public")
    public String publicPage() {
        return "Welcome to public page!";
    }
}

這樣就完成了一個簡單的身份驗(yàn)證和授權(quán)示例。當(dāng)用戶訪問不同的URL時,根據(jù)用戶的角色來進(jìn)行授權(quán)驗(yàn)證,如果用戶沒有相應(yīng)的角色,則會被拒絕訪問。

0