侧边栏壁纸
博主头像
Devlive 开源社区博主等级

行动起来,活在当下

  • 累计撰写 117 篇文章
  • 累计创建 32 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Spring Boot 整合 Security 权限控制-6:自定义failureHandler

我是管理员哦
2024-02-02 / 0 评论 / 0 点赞 / 9 阅读 / 4110 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2024-02-02,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

在 java 源码目录下创建hander文件夹, 在该文件夹下创建CustomAuthenticationFailHander类文件

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.hander;
 
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * CustomAuthenticationFailHander <br/>
 * 描述 : CustomAuthenticationFailHander <br/>
 * 作者 : qianmoQ <br/>
 * 版本 : 1.0 <br/>
 * 创建时间 : 2018-03-20 下午4:08 <br/>
 * 联系作者 : <a href="mailTo:shichengoooo@163.com">qianmoQ</a>
 */
@Component(value = "customAuthenticationFailHander")
public class CustomAuthenticationFailHander extends SimpleUrlAuthenticationFailureHandler {
 
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("登录失败!!!");
        this.returnJson(response, exception);
    }
 
    /**
     * 直接返回需要返回的 json 数据
     */
    private void returnJson(HttpServletResponse response,
                            AuthenticationException exception) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println("{\"ok\":0,\"msg\":\"" + exception.getLocalizedMessage() + "\"}");
    }
 
    /**
     * 直接返会错误页面
     */
    private void returnErrorPage(HttpServletRequest request, HttpServletResponse response,
                                 AuthenticationException exception) throws IOException, ServletException {
        String strUrl = request.getContextPath() + "/loginErrorPath";
        request.getSession().setAttribute("status", 0);
        request.getSession().setAttribute("message", exception.getLocalizedMessage());
        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
        // 使用该方法会出现错误
//        request.getRequestDispatcher(strUrl).forward(request, response);
        response.sendRedirect(strUrl);
    }
 
}

修改WebSecurityConfig配置文件支持自定义Handler

@Autowired
private CustomAuthenticationFailHander customAuthenticationFailHander;
 
 
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            // 允许直接访问/路径
            .authorizeRequests().antMatchers("/").permitAll()
            // 使其支持跨域
            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            // 其他路径需要授权访问
            .anyRequest().authenticated()
            // 指定登录页面
            .and().formLogin().loginPage("/user/login")
            // 指定登录失败跳转地址, 使用自定义错误信息
            .failureHandler(customAuthenticationFailHander)
            // 登录成功后的默认路径
            .defaultSuccessUrl("/").permitAll()
            // 退出登录后的默认路径
            .and().logout().logoutSuccessUrl("/user/login").permitAll();
}
0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区