spring-security入门4---自定义登录成功和登录失败的行为

文章目录

  • 1.前言
  • 2.默认行为演示
    • 2.1 spring-security登陆失败的默认行为
    • 2.2 spring-security登陆成功的默认行为
  • 3.自定义登录成功和登录失败的行为
  • 4.测试和验证
    • 4.1登陆失败
    • 4.2登陆成功

项目源码地址 https://github.com/nieandsun/security

1.前言

通过前几篇文章,尤其上篇文章第5部分的内容,可以知道spring-security默认的登陆行为是:登录成功后会跳转到引发登录的请求上去,但是有些场景下可能并不希望这样,本篇文章将介绍如何修改spring-security默认登陆成功和登陆失败的行为.

2.默认行为演示

首先在resources目录下新建一个简单的页面:demo.html
spring-security入门4---自定义登录成功和登录失败的行为_第1张图片

2.1 spring-security登陆失败的默认行为

spring-security入门4---自定义登录成功和登录失败的行为_第2张图片

2.2 spring-security登陆成功的默认行为

spring-security入门4---自定义登录成功和登录失败的行为_第3张图片

3.自定义登录成功和登录失败的行为

自定义登陆成功和登陆失败的行为其实很简单,具体步骤如下:

  • 自定义登录成功需要实现AuthenticationSuccessHandler接口并将其注入到spring容器中
package com.nrsc.security.security.config.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

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

/**
 * Created By: Sun Chuan
 * Created Date: 2019/6/18 19:32
 */
@Component(value = "NRSCAuthenticationSuccessHandler")
public class NRSCAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * Authentication封装了用户认证成功的信息
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication)
            throws IOException, ServletException {
        //设置返回内容的数据形式和编码格式
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //将户认证成功的信息以json数据的形式返回给前端
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(authentication));
    }
}
  • 自定义登录失败需要实现AuthenticationFailureHandler接口并将其注入到spring容器中
package com.nrsc.security.security.config.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

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

/**
 * Created By: Sun Chuan
 * Created Date: 2019/6/18 19:46
 */
@Component("NRSCAuthenticationFailureHandler")
public class NRSCAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     *   AuthenticationException里封装了用户登陆失败的错误信息
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        AuthenticationException e)
            throws IOException, ServletException {
        //修改状态码
        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        //设置返回内容的数据形式和编码格式
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        //将抓到的错误信息以json数据的形式进行返回
        httpServletResponse.getWriter().write(objectMapper.writeValueAsString(e));
    }
}
  • 在配置文件中指定要用上面两个类来处理登陆成功和登陆失败的行为
package com.nrsc.security.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private AuthenticationSuccessHandler NRSCAuthenticationSuccessHandler;

    @Autowired
    private AuthenticationFailureHandler NRSCAuthenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/authentication/require")//登陆时进入的url-->相当于进入登陆页面
                .loginProcessingUrl("/nrsc/signIn")//告诉spring-security点击登陆时访问的url为/nrsc/signIn
                                            // ---->当spring-security接收到此url的请求后,会自动调用
                                            //com.nrsc.security.security.action.NRSCDetailsService中的loadUserByUsername
                                            //进行登陆校验
                                                    
                .successHandler(NRSCAuthenticationSuccessHandler)//指定使用NRSCAuthenticationSuccessHandler处理登陆成功后的行为
                .failureHandler(NRSCAuthenticationFailureHandler)//指定使用NNRSCAuthenticationFailureHandler处理登陆失败后的行为
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/require", "/nrsc-login.html")//指定不校验的url
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable(); //关闭csrf
    }
}

4.测试和验证

4.1登陆失败

spring-security入门4---自定义登录成功和登录失败的行为_第4张图片

4.2登陆成功

spring-security入门4---自定义登录成功和登录失败的行为_第5张图片
由此,已经成功地自定义了登录成功和登录失败的行为.

你可能感兴趣的:(spring-security,spring-security)