我對 Spring Security 很陌生。在 Angular 中,我有一個自定義表單,可以將帖子發送到此控制器:
@RestController
public class LoginController {
@PostMapping("/login")
public ResponseEntity<String> login(@RequestBody User user) {
if (user.getUsername().equals("linda") && user.getPassword().equals("pass")) {
return ResponseEntity.ok("Access granted");
}
return ResponseEntity.badRequest().body("Access denied");
}
}
如果登錄成功,用戶應該可以訪問該頁面/welcome,否則該頁面應該被禁止。
這是我嘗試過的:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Config {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/welcome").hasAnyRole("ADMIN")
.anyRequest()
.authenticated()
.and()
.formLogin(form -> form.loginPage("/login").permitAll());
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsManager() {
var linda = User.builder()
.username("linda")
.password(passwordEncoder().encode("pass"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(linda);
}
}
當我呼叫/login時,我得到狀態405 - Method Not Allowed。

可能我做錯了一切。如何正確地做到這一點?
uj5u.com熱心網友回復:
在您的登錄端點中應該更新兩件事:
@PostMapping("login")應該@PostMapping("/login")您應該定義一個包含用戶名和密碼的類作為欄位,并將端點引數更新為以下內容:
public ResponseEntity<String> login(@RequestBody CustomUser customUser) {或者您可以按如下方式使用它:
public ResponseEntity<String> login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password) {
更新 :
Following your update, i've resimulate your scenario and the configuration is wrong as you've already mentioned.
配置應如下所示,無需創建登錄端點:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login", "/loginFailed").permitAll()
.antMatchers("/welcome").hasAnyRole("ADMIN").anyRequest()
.authenticated().and()
.formLogin(form -> form.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/welcome")
.failureUrl("/loginFailed"));
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsManager() {
UserDetails linda = User.builder().username("linda")
.password(passwordEncoder().encode("pass")).roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(linda);
}
但是,用戶名和密碼應按照“UsernamePasswordAuthenticationFilter”中的默認配置在查詢引數中提交。您可以通過實作自定義用戶名密碼身份驗證過濾器來更改默認行為。(檢查
端點:
@GetMapping("/welcome")
public ResponseEntity<String> welcome(Authentication authentication) {
return ResponseEntity.ok("Weclome [" authentication.getName() "]");
}
@GetMapping("/loginFailed")
public ResponseEntity<String> login() {
return ResponseEntity.ok("Failed to login");
}
希望能幫助到你
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/525620.html
標籤:爪哇弹簧靴弹簧安全
