使用UserDetailsS​​ervice实现Spring Security

时间:2018-05-15 20:40:37

标签: java spring spring-security

我一直在尝试使用UserDetailsS​​ervice设置Spring Security。例如,我使用baeldung's tutorial。该应用程序已启动,无任何例外,但验证不起作用。 目前,我为每个应用程序模块提供了一个核心spring java配置和spring java配置。

Core Spring Java conf:

public class AppInitializer implements WebApplicationInitializer {

@Override
@Autowired
public void onStartup(ServletContext container) throws ServletException {
    AnnotationConfigWebApplicationContext context = getContext();
    container.addListener(new ContextLoaderListener(context));

    container.setInitParameter("spring.profiles.active", "dev"); //Workaround for NamingException
    container.setInitParameter("spring.profiles.default", "dev"); //Workaround for NamingException
    container.setInitParameter("spring.liveBeansView.mbeanDomain", "dev"); //Workaround for NamingException

    ServletRegistration.Dynamic mainDispatcher =
            container.addServlet("dispatcher", new DispatcherServlet(context));
    ServletRegistration.Dynamic businessDispatcher =
            container.addServlet("businessDispatcher", BusinessAppConfig.createDispatcherServlet(context));
    ServletRegistration.Dynamic ppaDispatcher =
            container.addServlet("ppaDispatcher", PpaAppConfig.createDispatcherServlet(context));

    initDispatcher(mainDispatcher, 1, "/");
    initDispatcher(businessDispatcher, 2, "/business");
    initDispatcher(businessDispatcher, 3, "/ppa");
}

private void initDispatcher(ServletRegistration.Dynamic dispatcher, int loadOnStartUp, String mapping) {
    if (dispatcher == null) {
        System.out.println("Servlet" + dispatcher.getName() + " is already added");
    } else {
        dispatcher.setLoadOnStartup(loadOnStartUp);
        dispatcher.addMapping(mapping);
    }
}

public AnnotationConfigWebApplicationContext getContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(MvcConfiguration.class);
    return context;
}

@Bean(name = "propertyConfigurer")
public PropertySourcesPlaceholderConfigurer getPropertyPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    placeholderConfigurer.setLocation(new ClassPathResource("common.properties"));
    placeholderConfigurer.setLocation(new ClassPathResource("amazon.S3Storage.properties"));
    placeholderConfigurer.setLocation(new ClassPathResource("local.storage.properties"));
    placeholderConfigurer.setLocation(new ClassPathResource("log4j.properties"));
    placeholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
    return placeholderConfigurer;
}

}

用于业务模块的Spring java conf

@Configuration
public class BusinessAppConfig {

    public static Servlet createDispatcherServlet(AnnotationConfigWebApplicationContext context) {
        context.register(BusinessMvcConfig.class);
        context.register(BusinessHibernateConfig.class);
        context.register(BusinessSecurityConfig.class);
        return new DispatcherServlet(context);
    }
}

Spring Security java conf for a business module

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BusinessSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

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

    @Autowired
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(getPasswordEncoder());
        return authProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().authenticated().
                and().formLogin().permitAll().
                and().logout().permitAll();
    }

    @Bean(name = "passwordEncoder")
    public PasswordEncoder getPasswordEncoder(){
        return new BCryptPasswordEncoder(11);
    }
}

UserDetailsS​​ervice实现

@Service
public class UserDetailsServiceImpl extends BaseServiceImpl<User, UserRepository<User>> implements UserDetailsService, UserService {

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {

        User user = dao.findUserByLogin(login);

        if (user == null) {
            throw new UsernameNotFoundException(login);
        }

        return new UserPrincipal(user);
    }
}

基于用户模型的用户详细信息

public class UserPrincipal implements UserDetails, Serializable {

    private User user;

    public UserPrincipal(User user) {
        this.user = user;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return user.isAccountNonExpired();
    }

    @Override
    public boolean isAccountNonLocked() {
        return user.isAccountNonLocked();
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return user.isCredentialsNonExpired();
    }

    @Override
    public boolean isEnabled() {
        return user.isEnabled();
    }
}

在调试模式下,我遇到了几个异常

2018-05-16 22:23:51 DEBUG InjectionMetadata:74 - Registered injected element on class [business.config.BusinessSecurityConfig$$EnhancerBySpringCGLIB$$c0bd9f7f]: AutowiredMethodElement for public org.springframework.security.authentication.dao.DaoAuthenticationProvider business.config.BusinessSecurityConfig.authenticationProvider()
2018-05-16 22:23:51 DEBUG InjectionMetadata:74 - Registered injected element on class [business.config.BusinessSecurityConfig$$EnhancerBySpringCGLIB$$c0bd9f7f]: AutowiredMethodElement for public void business.config.BusinessSecurityConfig.configureGlobal(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) throws java.lang.Exception
2018-05-16 22:23:51 DEBUG DefaultListableBeanFactory:569 - Eagerly caching bean 'businessSecurityConfig' to allow for resolving potential circular references

AND

[org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration$$EnhancerBySpringCGLIB$$3d61bda9]: AutowiredMethodElement for public void org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration.setGlobalAuthenticationConfigurers(java.util.List) throws java.lang.Exception

2018-05-16 22:24:11 DEBUG AnnotationUtils:1889 - Failed to meta-introspect annotation interface org.springframework.beans.factory.annotation.Autowired: java.lang.NullPointerException

那么,这个配置有什么问题?

1 个答案:

答案 0 :(得分:0)

因此,在配置Spring Security时我犯了一些错误。 找到这些错误有助于分析调试消息。

在更改之前调试请求的消息:

2018-06-03 00:14:26 DEBUG DispatcherServlet:891 - DispatcherServlet with name 'dispatcher' processing GET request for [/]
2018-06-03 00:14:26 DEBUG RequestMappingHandlerMapping:312 - Looking up handler method for path /
2018-06-03 00:14:26 DEBUG RequestMappingHandlerMapping:319 - Returning handler method [public java.lang.String business.controller.HomePageController.getHomePage(java.util.Map<java.lang.String, java.lang.Object>)]
2018-06-03 00:14:26 DEBUG DefaultListableBeanFactory:254 - Returning cached instance of singleton bean 'homePageController'
2018-06-03 00:14:26 DEBUG DispatcherServlet:979 - Last-Modified value for [/] is: -1
2018-06-03 00:14:26 DEBUG DispatcherServlet:1319 - Rendering view [org.springframework.web.servlet.view.JstlView: name 'index'; URL [/WEB-INF/views/index.jsp]] in DispatcherServlet with name 'dispatcher'
2018-06-03 00:14:26 DEBUG DefaultListableBeanFactory:254 - Returning cached instance of singleton bean 'requestDataValueProcessor'
2018-06-03 00:14:26 DEBUG JstlView:168 - Forwarding to resource [/WEB-INF/views/index.jsp] in InternalResourceView 'index'
2018-06-03 00:14:26 DEBUG DispatcherServlet:1000 - Successfully completed request
2018-06-03 00:14:31 DEBUG DispatcherServlet:891 - DispatcherServlet with name 'dispatcher' processing GET request for [/business/project/new]
2018-06-03 00:14:31 DEBUG RequestMappingHandlerMapping:312 - Looking up handler method for path /business/project/new
2018-06-03 00:14:31 DEBUG RequestMappingHandlerMapping:319 - Returning handler method [public java.lang.String business.controller.ProjectController.newProject(org.springframework.ui.Model) throws java.lang.Exception]
2018-06-03 00:14:31 DEBUG DefaultListableBeanFactory:254 - Returning cached instance of singleton bean 'projectController'
2018-06-03 00:14:31 DEBUG DispatcherServlet:979 - Last-Modified value for [/business/project/new] is: -1

在这里我们可以看到两个请求。

  • 第一个请求“/”由mainDispatcher处理(请参阅 AppInitializer一开始)。
  • 第二个请求 / business / project / new 由处理 mainDispatcher 以及 businessDispatcher 处理程序。

问题是错误的道路。要解决此问题,您应该更改旧设置:

ServletRegistration.Dynamic businessDispatcher =
    container.addServlet("businessDispatcher", BusinessAppConfig.createDispatcherServlet(context));
initDispatcher(businessDispatcher, 2, "/business/*");

路径更改后的调试:

2018-06-03 20:33:43 DEBUG DispatcherServlet:891 - DispatcherServlet with name 'businessDispatcher' processing GET request for [/business/]
2018-06-03 20:33:43 DEBUG RequestMappingHandlerMapping:312 - Looking up handler method for path /
2018-06-03 20:33:43 DEBUG RequestMappingHandlerMapping:319 - Returning handler method [public java.lang.String business.controller.HomePageController.getHomePage(java.util.Map<java.lang.String, java.lang.Object>)]
2018-06-03 20:33:43 DEBUG DefaultListableBeanFactory:254 - Returning cached instance of singleton bean 'homePageController'
2018-06-03 20:33:43 DEBUG DispatcherServlet:979 - Last-Modified value for [/business/] is: -1
2018-06-03 20:33:43 DEBUG DispatcherServlet:1319 - Rendering view [org.springframework.web.servlet.view.JstlView: name 'index'; URL [/WEB-INF/views/index.jsp]] in DispatcherServlet with name 'businessDispatcher'
2018-06-03 20:33:43 DEBUG DefaultListableBeanFactory:254 - Returning cached instance of singleton bean 'requestDataValueProcessor'
2018-06-03 20:33:43 DEBUG JstlView:168 - Forwarding to resource [/WEB-INF/views/index.jsp] in InternalResourceView 'index'
2018-06-03 20:33:43 DEBUG DispatcherServlet:1000 - Successfully completed request

因此,您可以在此处看到 / business / project / 网址由正确的调度程序 - businessDispatcher处理。

此外,应更改控制器@ReqestMapping 从

@Controller
@RequestMapping(value = "/business/project")
public class ProjectController {

@Controller
@RequestMapping(value = "/project")
public class ProjectController {

要保护方法免受浏览器地址行中的直接输入URL的影响,需要进行下一步更改:

检查  securedEnabled = true,  prePostEnabled = true

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class BusinessSecurityConfig extends WebSecurityConfigurerAdapter {

每个控制器或特定方法都应注明 @PreAuthorize

@Controller
@RequestMapping(value = "/project")
@PreAuthorize("isAuthenticated()")
public class ProjectController {

OR

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String newProject (Model model) throws Exception {
    model.addAttribute(new Project());
    return "project/new";
}

注意如果未授权用户尝试访问受保护的方法,则会传播AuthenticationCredentialsNotFoundException。

要处理此类异常,请参阅here