与之相反:如何使用spring security手动注销用户?
在我的应用程序中,我已经注册了新用户屏幕,该屏幕发布到控制器,该控制器在db中创建新用户(并进行一些明显的检查).然后我希望这个新用户自动登录...我有点想要一些东西像这样 :
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
Run Code Online (Sandbox Code Playgroud)
编辑 好我几乎已经基于如何以Spring Security 3.1以编程方式登录用户的答案实现
Authentication auth = new UsernamePasswordAuthenticationToken(MyNewUser, null);
SecurityContextHolder.getContext().setPrincipal(MyNewUser);
Run Code Online (Sandbox Code Playgroud)
但是,在部署时,jsp无法访问我,MyNewUser.getWhateverMethods()而在正常登录过程之后也是如此.这个代码在名义上有效,但在登录时会抛出错误如下:
<sec:authentication property="principal.firstname" />
Run Code Online (Sandbox Code Playgroud) 我目前以编程方式(例如,当他们通过Facebook或其他方式登录而不是使用我的登录表单)登录用户时:
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(user, "", authorities)
);
Run Code Online (Sandbox Code Playgroud)
我想要做的是将用户登录,就好像他们在登录表单中设置了remember-me选项一样.所以我猜我需要使用RememberMeAuthenticationToken而不是UsernamePasswordAuthenticationToken?但是,我为key构造函数的参数添加了什么?
RememberMeAuthenticationToken(String key, Object principal, Collection<? extends GrantedAuthority> authorities)
Run Code Online (Sandbox Code Playgroud)
我有以下代码(尝试以编程方式记录用户):
List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
...
User tempUser = new User(correctUsername,
correctPassword,
true, true, true, true, // logging them in...
authorities // type is List<GrantedAuthority>
);
...
Authentication authentication
= new UsernamePasswordAuthenticationToken(tempUser, authorities);
// I'm using authorities again (List<GrantedAuthority>)
// is this the right spot for it?
...
// this is the line causing the error
authentication.setAuthenticated(true);
Run Code Online (Sandbox Code Playgroud)
当我尝试运行时,我得到以下内容:
java.lang.IllegalArgumentException: Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead
Run Code Online (Sandbox Code Playgroud)
请注意,我正在使用和对象authorities中的 …