spring安全认证服务器

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

我正在云应用的身份验证服务部分工作,我创建了以下安全配置类。

@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()部分是否真的需要它?

slhcrj9b

slhcrj9b1#

有几件事必须改变,但首先,您必须定义一个方法,为每个请求提供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 branch Authentication示例进行操作

相关问题