Spring Security 使用自定义控制器来完成登陆验证

Spring Security 下面简称为 Security 基于 spring-security 4.1

Security 的 WEB 扩展中 form 方式登陆使用的是过滤器方式,页面模版是可以定制的,但是如果需要登陆表单中有更多的选项,或者说需要在登陆的时候处理一些事情就变的很不方便。下面就是教你如何使用一个普通的控制器来完成登陆验证。

首先是制定 Security 的配置文件

http 节点中有一个属性 entry-point-ref 可以指定如果需要登陆将如何反应,在实现 AuthenticationEntryPoint 接口的类中有一个名称叫 LoginUrlAuthenticationEntryPoint 的类他可以实现需要登陆的时候产生 URL 跳转。

首先创建一个 LoginUrlAuthenticationEntryPoint bean


    
    

然后在 http 节点中配置 entry-point-ref
auto-config 可以关闭,因为不需要自动配置


    ...

http 节点内添加 intercept-url 防止拦截 /login 链接


如果需要记住我功能,需要在 http 节点内增加 remember-me 配置



最后可以增加一个退出过滤器
因为是过滤器拦截判断使用 /logout 不需要有对应的控制器
如果这个 /logout 中没有对应的控制器,需要添加 logout-success-url 跳转链接,防止访问 /logout URL 后候报 404 错误


最后需要配置 authentication-manager 节点中的 id 用来给控制器中注入使用


   ...

完整的配置文件代码



    
    
    
    

    

    
    

    
        
    

    
        
        
        
        
        
        
        
        
    
    
    
        
            
                
                
            
        
    
    

下面是控制器的代码部分

代码过程都是通过 debug 模式下在 UsernamePasswordAuthenticationFilter 中分析得出

@Controller
public class AuthController {
    @Autowired
    @Qualifier("authenticationManager") // bean id 在  中设置
    private AuthenticationManager authManager;
 
    @Autowired
    private SessionAuthenticationStrategy sessionStrategy;
 
    @Autowired(required = false)
    private RememberMeServices rememberMeServices;
 
    @Autowired(required = false)
    private ApplicationEventPublisher eventPublisher;
 
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(LoginForm form) {
        return "login";
    }
 
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String loginPost(@Valid LoginForm form, BindingResult result,
            HttpServletRequest request, HttpServletResponse response) {
        if (!result.hasErrors()) {
 
            // 创建一个用户名密码登陆信息
            UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(form.getUsername(), form.getPassword());
 
            try {
                // 用户名密码登陆效验
                Authentication authResult = authManager.authenticate(token);
 
                // 在 session 中保存 authResult
                sessionStrategy.onAuthentication(authResult, request, response);
 
                // 在当前访问线程中设置 authResult
                SecurityContextHolder.getContext().setAuthentication(authResult);
 
                // 如果记住我在配置文件中有配置
                if (rememberMeServices != null) {
                    rememberMeServices.loginSuccess(request, response, authResult);
                }
 
                // 发布登陆成功事件
                if (eventPublisher != null) {
                    eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
                }
                return "redirect:/";
            } catch (AuthenticationException e) {
                result.reject("authentication.exception", e.getLocalizedMessage());
            }
        }
        return "login";
    }
}

最后是 JSP 页面部分代码

页面都需要经过 Security 过滤器才能产生 csrf token,否则请关闭 csrf

登陆代码


    
    

用户名:

密码:

记住我:

退出代码

原创文章转载注明

你可能感兴趣的:(Spring Security 使用自定义控制器来完成登陆验证)