使用spring security调用“/authenticate”api时拒绝访问

qkf9rpyu  于 2021-07-23  发布在  Java
关注(0)|答案(1)|浏览(325)

我尝试通过/authenticate api进行身份验证以生成令牌,但它总是拒绝我访问,即使用户名和密码正确。问题是csrf()的int代码。disabled()。我试图从configure方法中删除csrf().disabled(),它确实消除了拒绝访问的问题,但是它没有给我任何响应,它没有生成jwt(没有任何响应)。
这是我的控制器:

@RestController
@RequestMapping("/api")
public class SecurityController {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private MyUserDetailService userDetailsService;

@Autowired
private JwtUtil jwtUtil;

@GetMapping("/test")
private String test() {
    return "Test";
}

@GetMapping("/hello")
private String hello() {
    return "hello";
}

@PostMapping("/authenticate")
public ResponseEntity<?> createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest)
        throws Exception {
    try {
        authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
                authenticationRequest.getUsername(), authenticationRequest.getPassword()));
    } catch (BadCredentialsException e) {
        throw new Exception("Incorrect username or password",e);
    }
    final UserDetails userDetails = userDetailsService.loadUserByUsername(authenticationRequest.getUsername());
    final String jwt = jwtUtil.generateToken(userDetails);
    return ResponseEntity.ok(new AuthenticationResponse(jwt));
}

}

securityconfig文件:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private MyUserDetailService myUserDetailService;

@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(myUserDetailService);
}

@Bean
public PasswordEncoder passwordEncoder() {
    return NoOpPasswordEncoder.getInstance();
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().authorizeRequests().antMatchers("/authenticate").permitAll().anyRequest()
            .authenticated();
}

 }

r1wp621o

r1wp621o1#

您的终结点名称是 /api/authenticate .
所以

.antMatchers("/authenticate")

行不通,你需要匹配正确的网址。

相关问题