其他分享
首页 > 其他分享> > Spring Security-从入门到精通-自定义登录成功/失败 url

Spring Security-从入门到精通-自定义登录成功/失败 url

作者:互联网

要想调到项目外部的链接该如何做

1 源码解析

一、点击successForwardUrl

二、在FormLoginConfigurer里面发现 用successHandler()这个方法做的跳转

三、点进ForwardAuthenticationSuccessHandler 发现 其实现了AuthenticationSuccessHandler这个接口

四、点击failureForwardUrl 也类似 也实现了 AuthenticationSuccessHandler

2 自定义 成功失败的跳转方式

package com.mangoubiubiu.security.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

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

public class ErrorHandler implements AuthenticationFailureHandler {

    private final String forwardUrl;

    public ErrorHandler(String forwardUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl), () -> {
            return "'" + forwardUrl + "' is not a valid forward URL";
        });
        this.forwardUrl = forwardUrl;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {


        response.sendRedirect(forwardUrl);
    }
}
package com.mangoubiubiu.security.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

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

@Slf4j
public class SuccessHandler implements AuthenticationSuccessHandler {
    private final String redictUrl;

    public SuccessHandler(String redictUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(redictUrl), () -> {
            return "'" + redictUrl + "' is not a valid forward URL";
        });
        this.redictUrl = redictUrl;
    }


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        log.info("---------------->authentication.getAuthorities()+{}",authentication.getAuthorities());
       //基于安全考虑 凭证不会显示 会显示null
        log.info("---------------->authentication.getCredentials()+{}",authentication.getCredentials());
        log.info("---------------->authentication.getDetails()+{}",authentication.getDetails());
        log.info("---------------->authentication.getPrincipal()+{}",authentication.getPrincipal());
        log.info("---------------->authentication.isAuthenticated()+{}",authentication.isAuthenticated());




        response.sendRedirect(redictUrl);

    }
}

配置类修改

package com.mangoubiubiu.security.config;

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.AuthenticationSuccessHandler;

/**
 * SecurityConfig 配置类
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
            //表单登录
            http.formLogin()
                    .loginProcessingUrl("/login")
                    .loginPage("/login.html")
                  // .successForwardUrl("/main")
                   //.failureForwardUrl("/toError")
                    .successHandler((AuthenticationSuccessHandler) new SuccessHandler("https://www.cnblogs.com/mangoubiubiu/"))
                    .failureHandler(new ErrorHandler("https://www.baidu.com/"))
                    //自定义登录用户名参数
                    .usernameParameter("user")
                    .passwordParameter("pwd");
            //所有请求都必须被认证(登录)
            http.authorizeRequests()
                    //放行登录页面
                    .antMatchers("/login.html","/error.html").permitAll()
                    //所有请求都必须被认证(登录)
                    .anyRequest().authenticated();

            //关闭 csrf 跨站请求伪造
            http.csrf().disable();
    }

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

}

 

 

 

 

标签:web,自定义,url,Spring,springframework,authentication,import,org,security
来源: https://www.cnblogs.com/mangoubiubiu/p/16211826.html