spring-security 登录端点返回403,在post man中禁止,但浏览器身份验证工作正常(Sping Boot )

sqyvllje  于 2022-11-11  发布在  Spring
关注(0)|答案(3)|浏览(291)

我正在尝试使用JWT保护/授权我的端点。令牌将在成功登录后生成。问题是每当我调用登录端点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并进行身份验证,它就能正常工作。
这是我的 Postman 请求x1c 0d1x
我启用了调试,以下是调用端点时的日志。

我不知道我做错了什么,请帮助。

f1tvaqid

f1tvaqid1#

将csrf.disable()和其他配置从**受保护的void configure(HttpSecurity http)方法移动到SecurityFilterChain筛选器链(HttpSecurity http)**方法。

说明:

这里的问题是SecurityConfig类。由于您的类没有扩展WebSecurityConfigurerAdapter,**受保护的void configure(HttpSecurity http)不会对您的应用程序产生任何影响。所有配置都是从SecurityFilterChain filterChain(HttpSecurity http)**方法的@Bean应用的。

irlmq6kh

irlmq6kh2#

将此代码替换为configure(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();

    }
vxqlmq5t

vxqlmq5t3#

将以下方法从:

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()添加到此方法中
你也发送用户名和密码从授权选项卡在 Postman 直接选择基本认证选项。并尝试访问任何受保护的链接。
[This将显示如何选择基本身份验证]

相关问题