有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Springsecurity以编程方式登录用户?

我需要以编程方式登录通过Facebook API认证的用户。原因是,每个用户都有很多相关的项目(例如购物车),因此,一旦用户使用Facebook API进行身份验证,我需要使用spring security登录用户,以便能够访问他/她的购物车

根据我的研究,有很多方法可以实现它,但在我从代码发送登录请求时,我无法部署其中任何一种方法,另一个问题是,有些人创建了用户对象,但他们没有解释如何创建它

那些创建了用户对象但没有解释如何创建的人

来自第一个示例:this answer

  Authentication auth = 
  new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

第二个例子:this one

  34.User details = new User(username);
  35.token.setDetails(details);

第三个例子:this one

  Authentication authentication = new UsernamePasswordAuthenticationToken(user, null,
  AuthorityUtils.createAuthorityList("ROLE_USER"));

另一个example is here,它没有帮助,因为我需要从自己的代码而不是从浏览器登录用户;因此,我不知道如何填充HttpServletRequest对象

protected void automatedLogin(String username, String password, HttpServletRequest request) {

麦可德

...
if(isAuthenticatedByFB())
{
    login(username);
    return "success";
}
else{
    return "failed";
}

共 (1) 个答案

  1. # 1 楼答案

    这段代码来自Grails' Spring Security Core -Plugin,它是根据Apache 2.0许可证发布的。我添加导入只是为了指出具体的类型。原作者是伯特·贝克维思

    import org.springframework.security.core.userdetails.UserCache;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    
    ...
    
    public static void reauthenticate(final String username, final String password) {
        UserDetailsService userDetailsService = getBean("userDetailsService");
        UserCache userCache = getBean("userCache");
    
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                userDetails, password == null ? userDetails.getPassword() : password, userDetails.getAuthorities()));
        userCache.removeUserFromCache(username);
    }
    

    getBean-方法仅从应用程序上下文提供bean