我正在嘗試使用 JWT 保護/授權我的端點。登錄成功后生成token。問題是每當我呼叫登錄端點 http://localhost:8080/login 并傳入憑據時,它都會回傳 403 回應。這是我的彈簧安全配置
@Configuration
public class SecurityConfig {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((authz) -> authz.anyRequest().authenticated()).httpBasic(withDefaults());
return http.build();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}
@Bean
public AuthenticationManager getAuthenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
protected void configure(HttpSecurity http) throws Exception{
http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated();
}
}
這是我的登錄控制器
@RestController
public class LoginController {
@Autowired
private JwtService jwtService;
@Autowired
AuthenticationManager authenticationManager;
@RequestMapping(value="/login", method=RequestMethod.POST)
public ResponseEntity<?> getToken(@RequestBody AccountCredentials credentials) {
// Generate token and send it in the response
//Authorization
// header
UsernamePasswordAuthenticationToken creds = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
Authentication auth = authenticationManager.authenticate(creds);
String jwts = jwtService.getToken(auth.getName());
return ResponseEntity.ok().header(HttpHeaders.AUTHORIZATION, "Bearer " jwts).
header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "Authorization").build();
}
}
這是我的 UserServiceImplementation
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository repository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Optional<User> user =
repository.findByUsername(username);
UserBuilder builder = null;
if (user.isPresent()) {
User currentUser = user.get();
builder =
org.springframework.security.core.userdetails.
User.withUsername(username);
builder.password(currentUser.getPassword());
builder.roles(currentUser.getRole());
} else {
throw new UsernameNotFoundException("User not found.");
}
return builder.build();
}
}
如果我在瀏覽器中訪問 http://localhost:8080/api 并進行身份驗證,它就可以作業。
這是我的郵遞員要求

我啟用了除錯,這是呼叫端點時的日志。

我不知道我做錯了什么,請幫助。
uj5u.com熱心網友回復:
將 csrf.disable() 和其他配置從受保護的 void configure(HttpSecurity http)方法移動到SecurityFilterChain filterChain(HttpSecurity http)方法。
說明:
這里的問題是您的 SecurityConfig 類。由于您的類沒有擴展 WebSecurityConfigurerAdapter,因此受保護的 void configure(HttpSecurity http)不會對您的應用程式產生任何影響。所有的配置都是從SecurityFilterChain filterChain(HttpSecurity http)方法的@Bean 應用的。
uj5u.com熱心網友回復:
用配置(HttpSecurity)替換此代碼。
protected void configure(HttpSecurity http) throws Exception{
http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.POST, "/login").permitAll().and().httpBasic();
}
uj5u.com熱心網友回復:
將以下方法從
protected void configure(HttpSecurity http) throws Exception{
http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated();
}
至 :
protected void configure(HttpSecurity http) throws Exception{
http.cors().and().csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests().httpBasic().and().antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated();
}
您必須將 httpBasic() 添加到此方法
您還可以通過選擇基本身份驗證選項直接從郵遞員的授權選項卡發送用戶名和密碼。并嘗試訪問任何受保護的鏈接。
[這將顯示如何選擇基本身份驗證]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/511705.html
