簡體   English   中英

具有UserDetailsS​​ervice實現的Spring Security

[英]Spring Security with UserDetailsService implementation

我一直在嘗試使用UserDetailsS​​ervice設置Spring Security。 作為示例,我使用了baeldung的tutorial 該應用程序已啟動,沒有任何異常,但身份驗證不起作用。 目前,每個應用模塊都有一個核心spring java config和spring java config。

核心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

@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);
    }
}

基於用戶模型的UserDetails

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

[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

那么,這種配置有什么問題呢?

因此,在配置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 / URL由正確的調度程序-businessDispatcher處理。

另外,控制器@ReqestMapping應該從

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

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

為了保護方法免受瀏覽器地址行中直接輸入URL的影響,需要進行以下更改:

檢查secureEnabled = 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 {

要么

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

請注意,如果未授權的用戶試圖訪問受保護的方法,則會傳播AuthenticationCredentialsNotFoundException。

要處理此類異常,請參見此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM