如何在不知道密码的情况下使用Spring Security以用户身份自动登录?

如何在不知道密码的情况下使用Spring Security以用户身份自动登录?,第1张

如何在不知道密码的情况下使用Spring Security以用户身份自动登录?

为了使其正常工作,我必须:

配置对UserDetailsS​​ervice(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的良好先驱



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5490179.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存