第二篇 也是很簡單 先把帳號密碼放在記憶體吧
配置有兩種
yml
application-dev.yml
1 2 3 4 5 6
| spring: security: user: name: 'sam' password: '1qaz2wsx' roles: 'ADMIN'
|
這樣就可以啟用 Basic Auth
測試
1 2 3
| curl -X GET \ http://localhost:8080 \ -H 'Authorization: Basic c2FtOjFxYXoyd3N4'
|
這樣就可以拿到回應了.
JavaConfiguration
可以做更多細部調整
ServerSecurityConfiguration.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| 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.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration @EnableWebSecurity public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("sam").password("{noop}1qaz2wsx").roles("USER") .and() .withUser("admin").password("{noop}password").roles("USER", "ADMIN"); }
protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest() .authenticated() .and() .httpBasic(); }
}
|
測試
1 2 3
| curl -X GET \ http://localhost:8080 \ -H 'Authorization: Basic c2FtOjFxYXoyd3N4'
|
一樣可以拿到資料
References
Spring REST + Spring Security Example
SAM的程式筆記 由朱尚禮製作,以創用CC 姓名標示-非商業性-相同方式分享 4.0 國際 授權條款釋出。