Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用webservice验证Spring安全性并从数据库检索角色_Java_Spring_Web Services_Spring Mvc_Spring Security - Fatal编程技术网

Java 使用webservice验证Spring安全性并从数据库检索角色

Java 使用webservice验证Spring安全性并从数据库检索角色,java,spring,web-services,spring-mvc,spring-security,Java,Spring,Web Services,Spring Mvc,Spring Security,我正在努力完成一件非常简单的事情,我相信一旦我做到了这一点,我会称自己为驴子。然而,以下是我试图在sudo代码中执行的步骤 step1 --get username and password from login form step2 -- send username and password to web service step3 -- if the return from the service equals "N" show error else if the return fro

我正在努力完成一件非常简单的事情,我相信一旦我做到了这一点,我会称自己为驴子。然而,以下是我试图在sudo代码中执行的步骤

step1
--get username and password from login form

step2
-- send username and password to web service

step3 
-- if the return from the service equals "N" show error else if the return from the service equals "Y" then authenticate a user and query database for user roles.

step4 
-- if the user role is not allowed to see page show error page else continue to page.
我试过几次教程,但都失败得很惨。我怀疑,因为我所看到的一切都与配置相关或与注释相关,所以我有点难以理解用户在什么时候被认证

我试过了


我最大的问题是上面的第三步。我该怎么做?我只是不明白如何对用户进行身份验证,并向该用户添加几个角色,以保持在spring的结构中

在使用Spring Security时,可以使用以下结构:

[在我的例子中,它是基于注释的,并带有Spring Boot。]

您将需要一个从WebSecurityConfigureAdapter扩展而来的ApplicationSecurity类

public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailSecurityService userDetailSecurityService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/static").permitAll().anyRequest()
                .fullyAuthenticated();

        http
                .csrf().disable()
                .formLogin().loginPage("/login").failureUrl("/login?error=1")
                .permitAll().defaultSuccessUrl("/")
                .successHandler(
                        new NoRedirectSavedRequestAwareAuthenticationSuccessHandler())
                .and()
                    .sessionManagement()
                    .sessionAuthenticationErrorUrl("/notauthorized")
                    .invalidSessionUrl("/notauthorized")
                .and()
                    .logout()
                    .deleteCookies("JSESSIONID", "SESSION")
                .permitAll();
    }

    //If you want to add some encoder method to store your passwords
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailSecurityService).passwordEncoder(passwordEncoder());
    }


    @Bean
    public PasswordEncoder passwordEncoder(){
        return new MD5PasswordEncoder();
    }


    private class NoRedirectSavedRequestAwareAuthenticationSuccessHandler extends
            SimpleUrlAuthenticationSuccessHandler {

        final Integer SESSION_TIMEOUT_IN_SECONDS = 30 * 60; /** 30 min */

        @Override
        public void onAuthenticationSuccess(HttpServletRequest request,
                                            HttpServletResponse response, Authentication authentication)
                throws ServletException, IOException {

            request.getSession().setMaxInactiveInterval(SESSION_TIMEOUT_IN_SECONDS);
            response.sendRedirect("/");
        }
    }
}
类UserDetailsSecurityService必须实现UserDetailsService,这是一个Spring安全类,需要重写方法loadUserByUsername()


对于成功和失败,您的web服务是否只返回Y和N?如果是,则很难得出您希望返回给客户端的错误类型,例如用户不存在、用户凭据无效或用户在数据库中不活动,理想情况下,web服务应该返回正确的响应以及用户数据(至少是角色),这样您就不需要再次查询数据库来获取角色。感谢apollo的响应。如果服务响应等于“n”,则返回“无效用户名/密码”错误。所以我真正的问题是上面的第三步。我想,但我不确定,我是否需要以某种方式使用用户详细信息服务,但我不确定我在做什么。@Miguel,但你使用的是spring security吗?因为如果您正在使用它,您不需要Web服务,您必须添加UserDetailsService@cralfaro是的,我正在尝试使用spring安全性,但是我看到的示例通常使用xml硬编码用户,他们从数据库中获得一个角色。我的障碍是我需要分别调用一个web服务和一个数据库,然后将其用作身份验证的源。在使用表单身份验证的.net中,我会调用一个web服务,而当服务响应时,我会从数据库中选择来获取用户角色。我正试图复制那个简单的功能。@Miguel好的,我明白了,然后我想我知道如何修复它,你知道在spring security中,你需要实现接口UserDetailsService,并在方法loadUserByUsername()中实现,然后在该方法的实现中你要做2件事,1调用你的WS。如果响应为Y,则转到DB并找到用户,并返回UserDetails,如果响应为N,则必须创建异常UserNotFoundException
@Service
public class UserDetailSecurityService implements UserDetailsService{

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        /*Here in your case would call your WebService and check if the result is Y/N and return the UserDetails object with all roles, etc
        If the user is not valid you could throw an exception
        */
        return userService.findByUsername(username);
    }
}