我正在嘗試練習彈簧安全性,這是我的彈簧安全性配置
@Configuration
@EnableWebSecurity
public class ProjectConfig extends WebSecurityConfigurerAdapter {
@Autowired
AuthenticationProvider authenticationProvider;
@Autowired
AuthenticationManagerBuilder builder;
@Bean
public AuthenticationManager global() throws Exception {
builder
.inMemoryAuthentication()
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("admin")
.password("123")
.authorities(() -> "ADMIN");
return builder.build();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/hello")
.authorizeRequests()
.anyRequest()
.authenticated();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
auth.parentAuthenticationManager(global());
}
}
這是我的自定義身份驗證提供程式:
@Component
public class CustomProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return BadCredentialsException("error");
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
我閱讀了有關如何為身份驗證管理器創建父級的資訊并嘗試對其進行測驗。每次我使用 Postman 發出請求時,我都會收到 403 錯誤。我的配置有什么問題? 郵差
uj5u.com熱心網友回復:
首先 Spring 使用ProviderManager類作為AuthenticationManager介面的實作,如果您看到該authenticate方法的實作,您會發現它僅在子結果null不是exception您的情況下才使用父身份驗證管理器。
if (result == null && this.parent != null) {
// Allow the parent to try.
try {
parentResult = this.parent.authenticate(authentication);
result = parentResult;
}
// other stuff
}
所以將以下代碼更改CustomProvider為回傳null
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
return AuthenticationException("error");
}
同樣從影像中我注意到您正在使用 http 基本身份驗證,但您沒有在配置中啟用它。
http
.antMatcher("/hello")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/341276.html
