【问题标题】:Spring security authentication serverSpring安全认证服务器
【发布时间】:2021-05-17 00:15:19
【问题描述】:

我正在开发云应用程序的身份验证服务部分,并创建了以下安全配置类。

@Configuration
@EnableWebSecurity
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
private final PasswordEncoder encoder;
private final UserService userService;
private final JwtConstant jwtConstant;

@Autowired
public JwtSecurityConfig(PasswordEncoder encoder, UserService userService, JwtConstant jwtConstant) {
    this.encoder= encoder;
    this.userService = userService;
    this.jwtConstant = jwtConstant;
}

@Bean
public DaoAuthenticationProvider getAuthenticationProvider() {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setPasswordEncoder(encoder);
    authenticationProvider.setUserDetailsService(userService);
    return authenticationProvider;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) {
    auth.authenticationProvider(getAuthenticationProvider());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilter(getAuthenticationFilter())
            .authorizeRequests()
            .antMatchers(HttpMethod.PUT, "/signup").permitAll()
            .anyRequest()
            .authenticated();
}

private AuthenticationFilter getAuthenticationFilter() throws Exception {
    return new AuthenticationFilter(authenticationManager(), jwtConstant);
}
}

我不确定 configure(HttpSecurity http) 方法的链式方法。身份验证服务只会接收“登录”和“注册”请求。

  • 我应该删除 authorizeRequests() 方法,因为我没有授权任何东西吗?
  • 我不确定 anyRequest().authenticated() 部分是否真的需要?

【问题讨论】:

    标签: java spring security


    【解决方案1】:

    有几件事需要更改,但首先,您必须定义一个方法,该方法将为每个请求提供 jwt,并且每个请求都应提供一个包含用户名和密码的 AuthRequest 对象:

    @RestController
    public class WelcomeController {
        @Autowired
        private JwtUtil jwtUtil;
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @PostMapping("/signup")
        public String generateToken(@RequestBody AuthRequest authRequest) throws Exception {
            try {
                authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(authRequest.getUserName(), authRequest.getPassword())
                );
            } catch (Exception ex) {
                throw new Exception("inavalid username/password");
            }
            return jwtUtil.generateToken(authRequest.getUserName());
        }
    }
    

    UserDetailsService 中,您可以进行如下身份验证:

    @Service
    public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {
        @Autowired
        private final UserRepository userRepository;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
            System.out.println("tried to loging : " + username);
            if(!Objects.isNull(username) && !"".equals(username)){
    
                Optional<User> user = userRepository.findUserByUserName(username);
    
                System.out.println(user.get());
                if(user.isPresent()){
    
                    User userParam = user.get();
                    return new org.springframework.security.core.userdetails.User(userParam.getUserName(),
                            userParam.getPassword(), new ArrayList<>());
                }
            }
            throw new UsernameNotFoundException("user does not exists or empty !!");
        }
    }
    

    对于配置方面:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        
        @Autowired
        private final UserDetailsService userDetailsService;
        @Autowired
        private final JwtFilter jwtFilter;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
        }
    
        @Bean
        public PasswordEncoder passwordEncoder(){
            
            return new BCryptPasswordEncoder(10);
        }
    
        @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests().antMatchers("/signup").permitAll()
                    .anyRequest().authenticated()
                    .and().exceptionHandling().and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
            http.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);;
        }
    }
    

    更多信息可以关注我的Github分支Authnticaition sample

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 2016-10-12
      • 2018-11-10
      • 2013-12-11
      • 2022-11-28
      • 2014-10-30
      • 2016-12-12
      相关资源
      最近更新 更多