spring boot 3 建立 Basic Authentication

URL Link //n.sfs.tw/16266

2023-11-10 11:23:03 By igogo

 

 

 

參考以下網站, 建立一個http basic authentication 為例

https://www.geeksforgeeks.org/authentication-and-authorization-in-spring-boot-3-0-with-spring-security/

https://docs.spring.io/spring-security/reference/servlet/architecture.html#servlet-securityfilterchain

https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html

 

pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

 

 

 

code

 

@SpringBootApplication
@RestController
public class BasicAuthApplication {

	public static void main(String[] args) {
		SpringApplication.run(BasicAuthApplication.class, args);
	}

	@RequestMapping("/")
	public String Index() {
		return "index page";
	}

	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

		http
				.authorizeHttpRequests((authorize) -> authorize
						.requestMatchers("/js/**").permitAll()
						.anyRequest().authenticated()
				)
				.csrf(c -> c.disable())
				.httpBasic(Customizer.withDefaults());


		return http.build();
	}

	@Bean
	public UserDetailsService userDetailsService() {
		User.UserBuilder users = User.withDefaultPasswordEncoder();
		UserDetails user =
				users
						.username("user")
                        .password("user")
						.roles("USER")
						.build();
		return new InMemoryUserDetailsManager(user);
	}

 

 

加入csrf

https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#csrf-components

 

 

測試

 

@SpringBootTest
@AutoConfigureMockMvc
class BasicAuthApplicationTests {


	@Autowired
	private MockMvc mockMvc;


	@Test
	void shouldReturnDefaultMessage() throws Exception {

		MvcResult mvcResult = mockMvc
				.perform(get("/hello").with(httpBasic("user","user")))
				.andReturn();

		System.out.println(mvcResult.getResponse().getContentAsString());
	}


}