第五节 自定义无权限的返回值

亮子 2021-07-19 03:48:25 17474 0 0 0

1、定义返回bean

package com.shenmazong.demosecurity0718.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
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: TODO
 * @date 2021/7/19 11:38
 */

@Component
@Slf4j
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        log.info("MyAccessDenied:handle,code="+httpServletResponse.getStatus());

        //设置响应状态码
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

        //设置响应数据格式
        httpServletResponse.setContentType("application/json;charset=utf-8");

        //输入响应内容
        PrintWriter writer = httpServletResponse.getWriter();
        String json = "{'code':-1,'message':'没有登录'}";

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

2)、设置生效

// 先绑定
@Resource
MyAccessDeniedHandler myAccessDeniedHandler;

// 再使用
http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);

完整配置类代码:

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;

    @Resource
    MyAccessDeniedHandler myAccessDeniedHandler;

    @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);

        // 设置没有权限的返回值
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
    }

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

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