【发布时间】:2017-05-26 10:34:43
【问题描述】:
我需要使用 spring boot 从我的应用程序 android 进行身份验证,我尝试像这样发送用户名和密码:
HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAuthorization(authHeader);
requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
并使用 restTemplate.exchange 发出网络请求:
ResponseEntity<Message> response = restTemplate.exchange(url, HttpMethod.POST,new HttpEntity<Object>(requestHeaders), Message.class);
但我仍然得到空响应。
这是我的代码服务器:
控制器:
@Controller
public class RController {
@RequestMapping(value={"/welcome"})
public @ResponseBody Message getMessage() {
return new Message(100, "Congratulations!", "You have accessed a Basic
Auth protected resource.");
}
@RequestMapping(value={"/login"})
public String login() {
return "login";
}
}
配置
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
DataSource dataSource;
@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery("select username,password, enabled from users where username=?")
.authoritiesByUsernameQuery("select username, role from user_roles where username=?");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout()
.permitAll();
http.exceptionHandling().accessDeniedPage("/403");
}
}
【问题讨论】:
-
尝试将
and().httpBasic()添加到您的configure(...)方法中 -
谢谢你,我会试试的
-
仍然无法正常工作:/ ...任何建议先生请
标签: android spring-boot resttemplate