【发布时间】:2014-10-13 10:22:23
【问题描述】:
我正在使用 spring security,它工作正常,但现在我想手动启动安全过程,对客户端进行更改,我需要在 my 控制器中获取用户名和密码(表单不会直接调用“j_spring_security_check”)
我想到了两个选项我都有一些问题:
-
在我得到参数并做一些事情后,我会向 j_spring_security_check url 发送一个 post 请求。我的代码:
public void test(loginDTO loginDTO) {
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); HttpHeaders headers = new HttpHeaders(); body.add( "j_username", loginDTO.getJ_username()); body.add( "j_password", loginDTO.getJ_password()); HttpEntity<?> httpEntity = new HttpEntity<Object>( body, headers); headers.add( "Accept", MediaType.APPLICATION_JSON_VALUE); restTemplate.exchange( "http://localhost:8080/XXX/j_spring_security_check", HttpMethod.POST, httpEntity, HttpServletResponse.class); }
这不起作用,我得到:500 内部服务器错误,为什么?
-
第二个选项 - 我做了以下:
public void test2(loginDTO loginDTO, HttpServletRequest request) { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( loginDTO.getJ_username(), loginDTO.getJ_password()); token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = this.authenticate(token); SecurityContextHolder.getContext().setAuthentication(authentication); this.sessionRegistry.registerNewSession( request.getSession().getId(), authentication.getPrincipal()); }问题是 onAuthenticationSuccess 没有被调用。感觉不对,我错过了使用 Spring Security 的意义。
正确的原因是什么?
【问题讨论】:
-
在大多数情况下,您认为您需要按照您的要求去做,但实际上您是从错误的角度看待问题(因此会遇到困难)。您能否更准确地说明您到底要解决什么问题,我可能会提出不同的方法?
-
问题是登录表单不在我的控制之下,它需要工作的方式是我的控制器使用用户名和密码获取登录 dto,我需要使用 spring security 对其进行身份验证.
标签: java spring spring-mvc spring-security