博主
258
258
258
258
专辑

第四节 自定义未登录错误

亮子 2021-07-19 03:33:30 4845 0 0 0

1、定义未登录异常类

package com.shenmazong.demosecurity0718.config;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

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

/**
 * @author 军哥
 * @version 1.0
 * @description: 自定义未登录返回信息的bean
 * @date 2021/7/19 11:19
 */

@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(401);

        PrintWriter writer = httpServletResponse.getWriter();
        String json = "{'code':0,'message':'没有登录'}";

        writer.write(json);
        writer.flush();
        writer.close();
    }
}

2、在配置中设置

        // 设置自定义未登录返回值
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint);

配置类完整代码:

package com.shenmazong.demosecurity0718.config;

import lombok.extern.slf4j.Slf4j;
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.authentication.builders.AuthenticationManagerBuilder;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

/**
 * @author 军哥
 * @version 1.0
 * @description: SpringSecurity配置类
 * @date 2021/7/18 17:45
 */

@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Resource
    MyAuthenticationProvider myAuthenticationProvider;

    @Resource
    MyAuthenticationEntryPoint myAuthenticationEntryPoint;

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

    @Override
    public void configure(WebSecurity web) throws Exception {
        log.info("configure:WebSecurity = ");
        super.configure(web);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                // 放行url
                .antMatchers("/login", "/index").permitAll()
                // 其他所有url请求都需要验证
                .anyRequest().authenticated()

                // 设定登录相关页面
                .and()
                .formLogin()
                .loginProcessingUrl("/process")
                .successForwardUrl("/success").
                failureForwardUrl("/failure")

                // 跨域請求关闭
                .and().csrf().disable()
                // 资源下载权限关闭
                .headers().frameOptions().disable();

        // 设置自定义未登录返回值
        http.exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        log.info("configure:AuthenticationManagerBuilder = ");

        // 使用自定义的验证类
        auth.authenticationProvider(myAuthenticationProvider);
    }
}