为了使其正常工作,我必须:
配置对UserDetailsService(jdbcUserService)的引用
<authentication-manager><authentication-provider><jdbc-user-service id="jdbcUserService" data-source-ref="dataSource" users-by-username-query="select username,password, enabled from users where username=?" authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username =? " /></authentication-provider></authentication-manager>
在我的控制器中自动连接我的userDetailsManager:
@Autowired@Qualifier("jdbcUserService") // <-- this references the bean idpublic UserDetailsManager userDetailsManager;
在同一控制器中,对用户进行身份验证,如下所示:
@RequestMapping("/automatic/login/test")public @ResponseBody String automaticLoginTest(HttpServletRequest request) { String username = "anyUserName@YourSite.com"; Boolean result = authenticateUserAndInitializeSessionByUsername(username, userDetailsManager, request); return result.toString();}public boolean authenticateUserAndInitializeSessionByUsername(String username, UserDetailsManager userDetailsManager, HttpServletRequest request){ boolean result = true; try { // generate session if one doesn't exist request.getSession(); // Authenticate the user UserDetails user = userDetailsManager.loadUserByUsername(username); Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); SecurityContextHolder.getContext().setAuthentication(auth); } catch (Exception e) { System.out.println(e.getMessage()); result = false; } return result;}
请注意,可以在此处找到仅对应用程序使用spring security的良好先驱。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)