首页 > 代码库 > 在spring security手动 自定义 用户认证 SecurityContextHolder
在spring security手动 自定义 用户认证 SecurityContextHolder
1.Spring Security 目前支持认证一体化如下认证技术:
HTTP BASIC authentication headers (一个基于IEFT RFC 的标准)
HTTP Digest authentication headers (一个基于IEFT RFC 的标准)
HTTP X.509 client certificate exchange (一个基于IEFT RFC 的标准)
LDAP (一个非常常见的跨平台认证需要做法,特别是在大环境)
Form-based authentication (提供简单用户接口的需求)
OpenID authentication
Computer Associates Siteminder
JA-SIG Central Authentication Service (CAS,这是一个流行的开源单点登录系统)
Transparent authentication context propagation for Remote Method Invocation and HttpInvoker (一个Spring远程调用协议)
2.但是有时不想使用这些认证,需要自定义用户认证
2.1 代码如下:
//从spring容器中获取UserDetailsService(这个从数据库根据用户名查询用户信息,及加载权限的service) UserDetailsService userDetailsService = (UserDetailsService)SpringContextUtil.getBean("userDetailsService"); //根据用户名username加载userDetails UserDetails userDetails = userDetailsService.loadUserByUsername(username); //根据userDetails构建新的Authentication,这里使用了 //PreAuthenticatedAuthenticationToken当然可以用其他token,如UsernamePasswordAuthenticationToken PreAuthenticatedAuthenticationToken authentication = new PreAuthenticatedAuthenticationToken(userDetails, userDetails.getPassword(),userDetails.getAuthorities()); //设置authentication中details authentication.setDetails(new WebAuthenticationDetails(request)); //存放authentication到SecurityContextHolder SecurityContextHolder.getContext().setAuthentication(authentication); HttpSession session = request.getSession(true); //在session中存放security context,方便同一个session中控制用户的其他操作 session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
2.2 方法userDetailsService.loadUserByUsername(username) 如下:
/** * 获取用户Details信息的回调函数. */ public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException { GeOperator geOperator = geOperatorService.findOperatorByPK(username); if(geOperator == null){ throw new UsernameNotFoundException("","用户名错误"); } //加载该用户权限 Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(geOperator); boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; boolean accountNonLocked = true; UserDetails userdetails = new MisUser(username, geOperator.getPwd(), geOperator, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths); return userdetails; }
参考问题:
How to manually set an authenticated user in Spring Security / SpringMVC
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。