security 登陆成功 访问 403_[SpringSecurity] 自定义403页面

eead1cd6d5ef58b1422d28ea71adf4f2.png

使用 Spring Security 时经常会看见 403(无权限),默认情况下 显示的效果如下:

08b2c2560f7fa74f2fafe727121a721e.png

而在实际项目中可能都是一个异步请求,显示上述效果对于用户 就不是特别友好了。

Spring Security 支持自定义权限受限。

具体做法

1.新建一个类实现AccessDeniedHandler重写handle方法

4711e3cafc0785b71ce5a2efbc290eff.png

2 配置类添加异常

c5f9c87421158c60151bc4d0e31bb1e6.png
package com.lin.springsecurity.handler;

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;

/**
 * 自定义403错误
 * @Author
 * @Date 2020/8/19 20:24
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //1 设置响应状态码 >这里设置403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json:charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("{"code":"403","msg":"无权限"}");
        writer.flush();
        writer.close();
    }
}
package com.lin.springsecurity.config;

import com.lin.springsecurity.handler.MyAccessDeniedHandler;
import com.lin.springsecurity.handler.MyAuthenticationFailureHandler;
import com.lin.springsecurity.handler.MyAuthenticationSuccessHandler;
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;

/**
 * @Author ccgg
 * @Date 2020/8/18 22:56
 * 创建 PasswordEncoder 实例,在spring启动时,注入容器中
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    /**
     * 创建加密对象
     * @return
     */
    @Bean
    public PasswordEncoder getPE(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单认证
        http.formLogin()
                //当发现login时认为是登录需要执行我们自定义的登录逻辑 >里面的url是登录页面表单的提交地址
               .loginProcessingUrl("/login")
                //登录成功后请求地址 请求方法必须是post的 这里是跳转控制器
              // .successForwardUrl("/toMain")
                .successHandler(new MyAuthenticationSuccessHandler("http://www.baidu.com"))
                //登录失败后请求访问的地址 >这里访问的是控制器
               //.failureForwardUrl("/failLogin")
                .failureHandler(new MyAuthenticationFailureHandler("/fail.html"))
                //设置登录页面
                .loginPage("/login.html")
                .usernameParameter("uuname")
                .passwordParameter("ppword")
        ;
        //url拦截认证  >所有请求都必须被认证 必须登录后才可以访问
        http.authorizeRequests()
                //设置不需要拦截的页面
                .antMatchers("/login.html").permitAll()
                .antMatchers("/fail.html").permitAll()
                //放行所有静态资源
                .antMatchers("/js/**","/css/**","/images/**").permitAll()
                //放行任意文件夹中以png结尾的图片
                .antMatchers("/**/*.png").permitAll()
                 //所有请求都必须被认真,必须登录后才能访问
                .anyRequest().authenticated();

        //关闭csrf防护 >只有关闭了,来自表单的请求
        http.csrf().disable();

        //异常处理
        http.exceptionHandling()
                .accessDeniedHandler(myAccessDeniedHandler);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自定义Spring Security中的403错误页面,可以按照以下步骤进行操作: 1. 创建一个403.html页面,用于显示自定义错误信息。 2. 创建一个自定义的AccessDeniedHandler类,用于处理访问被拒绝的情况。 3. 在Spring Security配置文件中配置AccessDeniedHandler,指定使用自定义的AccessDeniedHandler处理访问被拒绝的情况。 以下是一个简单的示例代码: 1. 创建403.html页面 ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Access Denied</title> </head> <body> <h1>Access Denied</h1> <p>You are not authorized to access this resource.</p> </body> </html> ``` 2. 创建自定义的AccessDeniedHandler类 ``` @Component public class CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException { response.sendRedirect("/403.html"); } } ``` 3. 在Spring Security配置文件中配置AccessDeniedHandler ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAccessDeniedHandler accessDeniedHandler; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated() .and() .formLogin() .and() .exceptionHandling().accessDeniedHandler(accessDeniedHandler); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER") .and() .withUser("admin").password("password").roles("USER", "ADMIN"); } } ``` 以上代码中,CustomAccessDeniedHandler类是自定义的AccessDeniedHandler实现类,它在处理访问被拒绝的情况时,通过重定向到403.html页面来显示自定义错误信息。在SecurityConfig配置类中,通过exceptionHandling().accessDeniedHandler(accessDeniedHandler)方法来指定使用自定义的AccessDeniedHandler处理访问被拒绝的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值