使用spring Security基于远程身份验证响应对用户进行身份验证

时间:2015-01-29 09:17:01

标签: java spring web-services spring-security basic-authentication

我遇到与this one类似的问题。我需要将用户凭据传递给远程基本身份验证并获得响应。我是Spring Security的新手,我不知道如何在我的代码中调用这个远程身份验证。在对引用问题的回答中,somone发布了一些Java代码,我有三个问题。

@Override
      protected UserDetails retrieveUser(String username,
            UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
         //Improve this line:
        String password = authentication.getCredentials().toString();
        // Invoke your webservice here
        GrantedAuthority[] grantedAuth = loginWebService.login(username, password);
        // create UserDetails. Warning: User is deprecated!
        UserDetails userDetails = new User(username, password, grantedAuth);
        return userDetails;
      }

1)我应该如何改进String password = authentication.getCredentials().toString();

2)// Invoke your webservice here如何调用该Web服务?

3)只是将这个类作为bean放在我的Java Config for Spring Security中吗?

编辑:我实现了目标,所以我将把这个实现留给其他可能遇到这个问题的人。您只需将其注册为bean并传递给authenticationProvider()

public class WebServiceAuthenticationProvider implements AuthenticationProvider {

    final static org.slf4j.Logger logger = LoggerFactory.getLogger(WebServiceAuthenticationProvider.class);

    @Value("${wsdl.remote.url}")
    String webpage;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        final String username = (String) authentication.getPrincipal();
        final String password = (String) authentication.getCredentials();
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        if (password == null || username == null) {
            throw new BadCredentialsException("Bad credentials");
        }

        Authenticator.setDefault(new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        username,
                        password.toCharArray());
            }
        });

        HashSet<GrantedAuthority> grantedAuth = new HashSet<>();

        String auth = username + ":" + password;
        byte[] authEncBytes = Base64.encodeBase64(auth.getBytes());
        String authStringEnc = new String(authEncBytes);

        URL url = null;
        try {
            url = new URL(webpage);
        } catch (MalformedURLException ex) {
            logger.debug("Malformed url {}!", webpage);
        }
        URLConnection connection = null;
        try {
            connection = url.openConnection();
        } catch (IOException ex) {
            logger.debug("IOException while opening url connection");
        }
        logger.debug("Authorization"+"Basic " + authStringEnc);
        connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        InputStream is = null;
        try {
            is = connection.getInputStream();
        } catch (IOException ex) {
            logger.debug("IOException while getting input stream");
            logger.debug("Authentication unsuccesfull");
            return authentication;
        }
        InputStreamReader isr = new InputStreamReader(is);
        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        try {
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }
        } catch (IOException ex) {
            logger.debug("IOException {}", ex.getMessage());
        }
        String result = sb.toString();
        logger.debug("Result: {}", result);

        if (result.length() != 0) {
            logger.debug("Äuthentication successfull");
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), grantedAuth);
            return token;
        } else {
            logger.debug("Äuthentication unsuccessfull");
            return authentication;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        logger.debug("Requested auth: {} {}", authentication, authentication.equals(UsernamePasswordAuthenticationToken.class));
        if (authentication.equals(UsernamePasswordAuthenticationToken.class)) {
            return true;
        } else {
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

1)你希望改进什么?

2)假设您正在访问RESTful API,您可以使用RestTemplate

3)如果您的JavaConfig扩展了WebSecurityConfigurerAdapter,您需要以这种方式定义它:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Bean
public UserDetailsService userDetailsService() {
    return new YourUserDetailService ();
}

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

[...]

}
相关问题