Jon*_*run 5 java rest spring spring-security
我想在我的应用程序中使用身份验证.我有一个Spring MVC应用程序和Spring Security应用程序.对浏览器,它工作正常.这意味着,我向我的应用程序验证用户并使用网页.
现在,我想用休息.我添加了不安全的控制器方法@ResponseBody,我在json中收到响应.但是如何使用RestTemplate用户和密码连接到我的应用程序?
我在RestClient中的代码是(用于测试):
public void unsecureProfileTest() {
String url = articleServiceUrl + "unsecure/profile/test.json";
url = articleServiceUrl + "secure/profile/wiew.json";
HttpEntity<Object> entity = new HttpEntity<Object>(getHeaders("user:userpassword"));
Object s = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
}
static HttpHeaders getHeaders(String auth) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON,
MediaType.TEXT_HTML));
byte[] encodedAuthorisation = Base64.encode(auth.getBytes());
headers.add("Authorization", "Basic "
+ new String(encodedAuthorisation));
return headers;
}
Run Code Online (Sandbox Code Playgroud)
我的安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/*").permitAll().and()
.formLogin().successHandler(successHandler)
.defaultSuccessUrl("/").failureHandler(failureHandler)
.failureUrl("/login?error=true").permitAll().and().logout()
.permitAll();
http.authorizeRequests().antMatchers("/resources/**").permitAll();
http.authorizeRequests().antMatchers("/welcome").permitAll();
http.authorizeRequests().antMatchers("/unsecure/**").permitAll();
http.authorizeRequests().antMatchers("/secure/*").authenticated();
http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
Run Code Online (Sandbox Code Playgroud)
结果是:访问被拒绝.我想问题来自restTemplate的身份验证,但我如何进行身份验证?
我的第二个问题是关于csrf谁被禁用但我想启用它(我的表单使用它)
我正在使用Spring 4.0和Spring Security 3.2
编辑 我更新了我的代码
String url = articleServiceUrl + "unsecure/profile/test.json";
url = articleServiceUrl + "secure/profile/wiew.json";
HttpEntity<Object> entity = new HttpEntity<Object>(getHeaders("{user:userpassword, password:userpassword}"));
Object s = restTemplate.exchange(url, HttpMethod.GET, entity, Object.class);
Run Code Online (Sandbox Code Playgroud)
我收到了一个代码 302
编辑18022014 - 16:46 我更新到
String url = articleServiceUrl + "login?username=user&password=userpassword";
HttpEntity entity restTemplate;exchange(url, HTTPMethod.POST,null, HttpEntity.class)
system.out.println(entity);
Run Code Online (Sandbox Code Playgroud)
在Web服务器的日志中,我收到了一条成功消息(请参阅"user"的userdetails).
现在,我想使用身份验证来访问其他URL("secure/profile/view.json")
如何保持身份验证?
谢谢
我一直在使用 spring security 和 spring boot REST 应用程序,并且创建了自己的MapCsrfTokenRepository,而不是默认的HttpSessionCsrfTokenRepository。
然后你可以为你的其余 URI 启用 csrf
http.csrf().csrfTokenRepository(tokenRepository)
Run Code Online (Sandbox Code Playgroud)
主要思想是当客户端使用GET访问/login资源时返回新的 CSRF_TOKEN ,因为 GET 不需要 csrf 令牌。然后客户端必须在下一次调用中使用此令牌。
例子在github上
| 归档时间: |
|
| 查看次数: |
8231 次 |
| 最近记录: |