使用 spring security 以编程方式登录用户 [英] Programmatically log-in a user using spring security

查看:26
本文介绍了使用 spring security 以编程方式登录用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相反的:如何使用spring security手动注销用户?

在我的应用程序中,我有注册新用户屏幕,它发布到一个控制器,该控制器在数据库中创建一个新用户(并进行一些明显的检查).然后我希望这个新用户自动成为登录......我有点想要这样的东西:

In my app I have register new user screen, which posts to a controller which creates a new user within db (and does a few obvious checks).I then want this new user to be automatically logged in ... I kind of want somethign like this :

SecurityContextHolder.getContext().setPrincipal(MyNewUser);

编辑好吧,我几乎已经根据 How to programmatically log user in with Spring Security 3.1

Edit Well I have almost implemented based on the answer to How to programmatically log user in with Spring Security 3.1

 Authentication auth = new UsernamePasswordAuthenticationToken(MyNewUser, null);
 SecurityContextHolder.getContext().setPrincipal(MyNewUser);

但是,在部署后,jsp 无法访问我的 MyNewUser.getWhateverMethods(),而在遵循正常登录程序时却可以访问.正常工作但在登录时抛出错误的代码如下:

However, when deployed the jsp can not access my MyNewUser.getWhateverMethods() whereas it does when normal login procedure followed. the code that works nomrally, but throws an error when logged in like above is below :

<sec:authentication property="principal.firstname" /> 

推荐答案

在我的控制器中,我有这个,它可以正常登录用户 :

In my controller i have this, which logs user in as normal :

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

SecurityContextHolder.getContext().setAuthentication(auth);

其中 user 是我新创建的自定义用户对象(实现 UserDetails).getAuthorities() 方法执行此操作(只是因为我的所有用户都具有相同的角色):

Where user is my custom user object(implementing UserDetails) that is newly created. The getAuthorities() method does this (just because all my users have the same role):

public Collection<GrantedAuthority> getAuthorities() {
        //make everyone ROLE_USER
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
        GrantedAuthority grantedAuthority = new GrantedAuthority() {
            //anonymous inner type
            public String getAuthority() {
                return "ROLE_USER";
            }
        }; 
        grantedAuthorities.add(grantedAuthority);
        return grantedAuthorities;
    }

这篇关于使用 spring security 以编程方式登录用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆