【Spring Security】AuthenticationSuccessHandler 用户认证成功后处理

文章目录

    • 前言
    • 简单介绍官方默认用户认证失败后处理器
      • SimpleUrlAuthenticationSuccessHandler
      • ForwardAuthenticationSuccessHandler
      • SavedRequestAwareAuthenticationSuccessHandler
    • 自定义
    • SecurityConfiguration 配置


前言

AuthenticationSuccessHandler 接口的作用是做用户认证成功后执行的操作处理器;官方目前是给了三个默认的处理器,我们也可以自定义处理器,接下来先简单介绍一下官方的,然后再用一个小例子自定义一个自己的。



简单介绍官方默认用户认证失败后处理器

SimpleUrlAuthenticationSuccessHandler

认证成功后重定向到某个URL。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 认证失败后处理器
			.successHandler(authenticationSuccessHandler());
}

@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
	SimpleUrlAuthenticationSuccessHandlerhandler = new SimpleUrlAuthenticationSuccessHandler();
	// 认证成功后重定向的URL
	handler.setDefaultTargetUrl("/login-success");
	return handler;
}

ForwardAuthenticationSuccessHandler

认证成功后跳转到某个URL。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 认证失败后处理器
			.successHandler(authenticationSuccessHandler());
}

@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
	// 验证成功后跳转的URL
	return new ForwardAuthenticationSuccessHandler("/login-success");
}

SavedRequestAwareAuthenticationSuccessHandler

用户成功登录后执行操作,它的特点是能够记住用户最初请求的URL,并在登录成功后重定向用户回到这个URL。
比方说你在网上浏览,找到了一个很有趣的视频链接,点击进去后发现需要登录才能观看。你登录账号后,网站自动跳转回你想看的那个视频,而不是让你重新开始浏览。这里,网站的登录系统就起到了 SavedRequestAwareAuthenticationSuccessHandler 的作用,确保你在登录后可以直接观看之前选择的视频。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 自定义登录页面
			.loginPage("/login")
			// 认证失败后处理器
			.successHandler(authenticationSuccessHandler());
}

@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
	SavedRequestAwareAuthenticationSuccessHandler authSuccessHandler = new SavedRequestAwareAuthenticationSuccessHandler();
	// 验证成功后默认跳转的URL
	authSuccessHandler.setDefaultTargetUrl("/defaultPage");
	return authSuccessHandler;
}


自定义

package com.security.handler.auth;

import com.alibaba.fastjson2.JSON;
import com.security.controller.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
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;


@Component
@Slf4j
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("AuthenticationSuccessHandlerImpl 登录认证成功时调用 ...");

        /**
         * 设置响应状态值
         */
        response.setStatus(200);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        // TODO 这里的 JSON 如果你有 Body 返回值的话可以不设置
        String json = JSON.toJSONString(
                ResponseResult.builder()
                        .code(200)
                        .message("登录成功!")
                        .build());

        // JSON信息
        response.getWriter().println(json);

    }
}


SecurityConfiguration 配置

package com.security.config;

import com.security.handler.auth.AuthenticationFailureHandlerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.cors.CorsConfiguration;

@Configuration
@EnableWebSecurity
// 开启限制访问资源所需权限
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurationTest extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        http
                // 登录
                .formLogin()
                // 认证成功后处理器
                .successHandler(authenticationSuccessHandler());
    }

    @Bean
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
    	// 自定义的成功后的处理器
        return new AuthenticationSuccessHandlerImpl();
    }
}




End


你可能感兴趣的:(#,Spring,Security,spring,java,后端)