本文介绍了如何自动登录与使用的Spring Security不知道他们的密码的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用Spring Security和我的客户要求:

My application uses Spring Security, and my client requires:


  • 的用户能够注册后,自动登录

  • 管理员登录任何用户不知道自己的密码。

所以,我需要弄清楚如何登录任何用户自动地不知道自己的密码。

So I need to figure out how to login as any user automatically without knowing their password.

这怎么能使用Spring Security的实现。

How can this be accomplished using Spring Security.

推荐答案

要得到这个工作,我不得不

To get this to work, I had to:

配置给UserDetailsS​​ervice(jdbcUserService)的参考

Configure a reference to the 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在我的控制器:

Autowire my userDetailsManager in my controller:

@Autowired
@Qualifier("jdbcUserService")  // <-- this references the bean id
public UserDetailsManager userDetailsManager;

在同一个控制器,验证我的用户像这样:

In the same controller, authenticate my user like so:

@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;
}

请注意,一个良好的precursor只以Spring Security为您的应用程序的

Note that a good precursor to just using spring security for your app can be found here.

这篇关于如何自动登录与使用的Spring Security不知道他们的密码的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 11:36