[英]Authenticate user with spring Security based on remote authentication response
I have similar problem to this one . 我也有类似的问题这一个 。 I need to pass user credentials to remote basic authentication and get response.
我需要将用户凭据传递给远程基本身份验证并获得响应。 I'm new to Spring Security and I don't know how to invoke this remote authentication inside my code.
我是Spring Security的新手,我不知道如何在代码中调用此远程身份验证。 In the answer to the referenced question somone posted some Java code and I have three question to it.
在所引用问题的答案中,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) How should I improve String password = authentication.getCredentials().toString();
1)我应该如何改善
String password = authentication.getCredentials().toString();
2) // Invoke your webservice here
how to invoke that webservice? 2)
// Invoke your webservice here
如何调用该Web服务?
3) Is simply putting this class as a bean in my Java Config for Spring Security enough? 3)只需将此类作为bean放在Java Config中以用于Spring Security就足够了吗?
EDIT: I achieved my goal so I will leave this implementation here for others who may come across this question. 编辑:我实现了我的目标,所以我将把此实现留给其他可能遇到此问题的人。 You just need to register this as a bean and pass to
authenticationProvider()
您只需要将其注册为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) What do you wish to improve? 1)您想改进什么?
2) Assuming you are accessing a RESTful API, you could use a RestTemplate
. 2)假设您正在访问RESTful API,则可以使用
RestTemplate
。
3) If your JavaConfig extends the WebSecurityConfigurerAdapter you need to define it in this way: 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());
}
[...]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.