spring-security Spring安全性:在Sping Boot 2.7.5中升级已停用的WebSecurityConfigurerAdapter

jfewjypa  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(467)

我尝试在不使用WebSecurityConfigurerAdapter的情况下更新我的应用程序,我需要帮助。代码是更改前后的代码。我不确定authenticationManager。我使用了多个网站来重构代码。
之前:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private CustomPasswordEncoder customPasswordEncoder;
    @Autowired
    private JwtFilter jwtFilter;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(customPasswordEncoder
                        .getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http = http.cors().and().csrf().disable();

        // Set session management to stateless
        http = http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and();

        // Set unauthorized requests exception handler
        http = http
                .exceptionHandling()
                .authenticationEntryPoint(
                        (request, response, ex) -> {
                            response.sendError(
                                    HttpServletResponse.SC_UNAUTHORIZED,
                                    ex.getMessage()
                            );
                        }
                )
                .and();

        // Set permissions on endpoints
        http.authorizeRequests()
                .antMatchers("/api/auth/**").permitAll()
                .antMatchers("/swagger-ui/**").permitAll()
                .antMatchers("/v3/api-docs/**").permitAll()
                .antMatchers("/error**").permitAll()
                .anyRequest().authenticated();

        // Add JWT token filter
        http.addFilterBefore(
                jwtFilter,
                UsernamePasswordAuthenticationFilter.class
        );

    }

}

在不使用WebSecurityConfigurerAdapter的情况下重构代码后:

@EnableWebSecurity
public class SecurityConfig{

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private CustomPasswordEncoder customPasswordEncoder;
    @Autowired
    private JwtFilter jwtFilter;

    @Bean
    AuthenticationManager authenticationManager(AuthenticationManagerBuilder builder) throws Exception {
        return builder.userDetailsService(userDetailsService)
                .passwordEncoder(customPasswordEncoder.getPasswordEncoder())
                .and().build();
    }

    public SecurityFilterChain configure(HttpSecurity http) throws Exception {

        http = http.cors().and().csrf().disable();

        // Set session management to stateless
        http = http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and();

        // Set unauthorized requests exception handler
        http = http
                .exceptionHandling()
                .authenticationEntryPoint(
                        (request, response, ex) -> {
                            response.sendError(
                                    HttpServletResponse.SC_UNAUTHORIZED,
                                    ex.getMessage()
                            );
                        }
                )
                .and();

        // Set permissions on endpoints
        http.authorizeRequests()
                .antMatchers("/api/auth/**").permitAll()
                .antMatchers("/swagger-ui/**").permitAll()
                .antMatchers("/v3/api-docs/**").permitAll()
                .antMatchers("/error**").permitAll()
                .anyRequest().authenticated();

        // Add JWT token filter
        http.addFilterBefore(
                jwtFilter,
                UsernamePasswordAuthenticationFilter.class
        );

        return http.build();
    }

}

最后,这是我的AuthController。在SecurityConfig中执行更改后,应用程序停止工作,并出现一个巨大的错误。“org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“org.springframework.security.config.annotation.web.configuration. Web安全配置”的Bean时出错:未满足通过方法“setFilterChains”参数0表达的依赖项;嵌套的异常是一个不满足的依赖关系异常:创建在类路径资源[org/springframework/ Boot /autoconfigure/security/servlet/SpringBootWebSecurityConfiguration$SecurityFilterChainConfiguration.class]中定义的名为'defaultSecurityFilterChain'的Bean时出错:未满足通过方法“defaultSecurityFilterChain”参数0表示的依赖项;嵌套的异常是一个嵌套的异常。创建在类路径资源[org/springframework/security/config/annotation/web/configuration/HttpSecurityConfiguration.class]中定义的名为“org.springframework.security.config.annotation.web.configuration. HttpSecurityConfiguration. httpSecurity”的Bean时出错:通过工厂方法示例化Bean失败;嵌套的异常是一个嵌套的异常。无法示例化[org.springframework.security.config.annotation.web.builders.HttpSecurity]:工厂方法“httpSecurity”引发了异常;嵌套的异常是java.lang.IllegalStateException:无法将org.springframework.security.config.annotation.authentication.configuration.authenticationConfiguration$EnableGlobalAuthenticationAutowiredConfigurer@53da2aec应用于已生成的对象”

package io.qbeat.tmregistrationtool.web;

import io.jsonwebtoken.ExpiredJwtException;
import io.qbeat.tmregistrationtool.domain.User;
import io.qbeat.tmregistrationtool.dto.AuthCredentialsRequest;
import io.qbeat.tmregistrationtool.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    private String domain;
    @PostMapping("login")
    public ResponseEntity <?> login (@RequestBody AuthCredentialsRequest request){
        try {
            Authentication authenticate = authenticationManager
                    .authenticate(
                            new UsernamePasswordAuthenticationToken(
                                    request.getUsername(), request.getPassword()
                            )
                    );

            User user = (User) authenticate.getPrincipal();
            user.setPassword(null);
            return ResponseEntity.ok()
                    .header(
                            HttpHeaders.AUTHORIZATION,
                            jwtUtil.generateToken(user)
                    )
                    .body(user);
        } catch (BadCredentialsException ex) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

    @GetMapping("/validate")
    public ResponseEntity<?> validateToken(@RequestParam String token,
                                           @AuthenticationPrincipal User user) {
        try {
            Boolean isValidToken = jwtUtil.validateToken(token, user);
            return ResponseEntity.ok(isValidToken);
        } catch (ExpiredJwtException e) {
            return ResponseEntity.ok(false);
        }
    }
}

任何帮助都将不胜感激。

huwehgph

huwehgph1#

我终于设法修复了我的问题。问题出在AuthenticationManager上。

@Bean
    public AuthenticationManager authenticationManagerBean(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(customPasswordEncoder.getPasswordEncoder());
        return authenticationManagerBuilder.build();
    }

相关问题