如何以编程方式使用Spring Security 3.1登录用户

时间:2011-09-30 18:29:06

标签: spring spring-mvc spring-security spring-3

在Spring和Spring Security 3.1中以特定用户名以编程方式登录Web访问者的正确方法是什么?看起来我在2.5下做的方式已经改变了一点。我相信现在有更好的办法。

基本上,当我创建一个新用户时,我还需要同时登录它们。

3 个答案:

答案 0 :(得分:18)

创建Authentication(通常为UsernamePasswordAuthenticationToken)然后调用

SecurityContextHolder.getContext().setAuthentication(authentication)

答案 1 :(得分:2)

如果您有兴趣为测试目的这样做,可以这样做:

    UserDetails user = _userService.loadUserByUsername(username);
    TestingAuthenticationToken token = new TestingAuthenticationToken(user,null);
    SecurityContextHolder.getContext().setAuthentication(token);

用户服务是实现UserDetailsS​​ervice的东西

答案 2 :(得分:0)

你可以写一个custom UsernamePasswordAuthenticationFilter来扩展Spring的UsernamePasswordAuthenticationFilter

以下是代码:

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, authResult);
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authResult;
        WebAuthenticationDetails details = (WebAuthenticationDetails) token.getDetails();
        String address = details.getRemoteAddress();
        User user = (User) authResult.getPrincipal();
        String userName = user.getUsername();
        System.out.println("Successful login from remote address: " + address + " by username: "+ userName);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        super.unsuccessfulAuthentication(request, response, failed);
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) failed.getAuthentication();
        WebAuthenticationDetails details = (WebAuthenticationDetails) token.getDetails();
        String address = details.getRemoteAddress();
        System.out.println("Failed login try from remote address: " + address);
    }
}