java 安全登录_java – Spring安全:以编程方式登录

我们正在开发一个带有jQuery mobile的移动应用程序,并且想要在

Spring 3.1.x后端上以编程方式对用户进行身份验证,并使用spring security进行正确设置.

POST请求被发送到包含用户名和密码的后端(使用jQuery的$.post),然后服务器验证凭据是否正确并登录用户.

服务器似乎在SecurityContext中正确设置了身份验证,但是当我们向服务器发出第二个请求($.get到需要登录的页面)时,安全细节似乎不会被记住,并且匿名令牌似乎是在上下文中.

这是控制器中处理登录的方法(为简洁起见,删除了密码检查):

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")

@ResponseBody

public Map login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {

Map response = new HashMap();

User u = userService.findByAccountName(username);

if (u != null && u.hasRole("inspector")) {

UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

try {

Authentication auth = authenticationManager.authenticate(token);

SecurityContextHolder.getContext().setAuthentication(auth);

response.put("status", "true");

return response;

} catch (BadCredentialsException ex) {

response.put("status", "false");

response.put("error", "Bad credentials");

return response;

}

} else {

response.put("status", "false");

response.put("error", "Invalid role");

return response;

}

}

这是我们从上下文中获取用户详细信息的另一种方法:

@RequestMapping(value = "/project", method = RequestMethod.GET)

@ResponseBody

public String getProjects(HttpSession session) {

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

User u = userService.findByAccountName(((UserDetails) authentication.getPrincipal()).getUsername());

...

Spring安全配置:

authentication-failure-url="/?login_error=t"/>

...

...

这应该根据spring安全文档和其他在线资源工作.关于什么可能出错的任何想法?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值