java[服务器端]中的验证spring rest服务
我有一个spring项目,它向其他人公开了一些api,但他们需要进行身份验证才能使用该服务java[服务器端]中的验证spring rest服务,java,spring,rest,spring-mvc,spring-security,Java,Spring,Rest,Spring Mvc,Spring Security,我有一个spring项目,它向其他人公开了一些api,但他们需要进行身份验证才能使用该服务 @Configuration @EnableWebSecurity public class SecConfig extends WebSecurityConfigurerAdapter{ @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exceptio
@Configuration
@EnableWebSecurity
public class SecConfig extends WebSecurityConfigurerAdapter{
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin")
.roles("USER");
}
}
当我使用这个spring配置时,我能够使用下面的客户机项目来验证和使用服务
public void getRestValue() {
final String url = "http://localhost:8080/template/getData";
final String username = "admin@admin.com";
final String password = "admin";
// Populate the HTTP Basic Authentitcation header with the username and
// password
RestTemplate restTemplate = new RestTemplate();
String plainCreds = username + ":" + password;
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(url,
HttpMethod.GET, request, String.class);
System.out.println(response);
String account = response.getBody();
System.out.println(account);
}
请告诉我哪里出了问题您的客户端使用HTTP基本身份验证,但您的服务器仅配置为表单身份验证。尝试在您的
配置(HttpSecurity http)
方法中添加.httpBasic()
。调试日志会说什么?我一调用rest服务,就会在响应正文中看到登录页面html。我也尝试添加了它。在这种情况下,即使是在浏览器中尝试时也禁用了可用的身份验证。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
AppUserDetailsService appUserDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(appUserDetailsService);
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring().antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/setup/*")
.permitAll().antMatchers("/login").permitAll()
.antMatchers("/logout").permitAll().anyRequest()
.authenticated().and().formLogin().loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("j_username")
.passwordParameter("j_password").failureUrl("/login")
.defaultSuccessUrl("/").permitAll().and().logout()
.logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/login").deleteCookies("JSESSIONID")
.invalidateHttpSession(true);
}
}