【Spring Boot】Spring Security登陆异常出路

Security 配置

package cn.young.greenhome.config;

import cn.young.greenhome.module.auth.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 安全配置类
 *
 * @author ycx
 * @since 2020-02-02
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    /**
     * 配置拦截请求
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/login", "/logout", "/getVerifyCode", "/validateVerifyCode")
                .permitAll()
                .anyRequest().authenticated()

                .and()
                .formLogin()
                .loginPage("/login")
                .successForwardUrl("/success")
                .failureForwardUrl("/failure")

                .and()
                .logout()
                .logoutUrl("/logout")
                .invalidateHttpSession(true)

                .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 123456
        // $2a$10$E0ypqva9V.tMStGszN8Zeu6mUAO2OkEUs1bbYGUIvnANVuwi5DfgO
        // 自定义用户服务和密码
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    /**
     * 配置过滤器
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略静态资源
        web.ignoring().antMatchers("/static/**");
        super.configure(web);
    }

}

出异常时forward到 /failure

点击 failureForwardUrl 方法

    public FormLoginConfigurer<H> failureForwardUrl(String forwardUrl) {
        this.failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl));
        return this;
    }

异常信息被存储在了request中

public class ForwardAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final String forwardUrl;

    /**
     * @param forwardUrl
     */
    public ForwardAuthenticationFailureHandler(String forwardUrl) {
        Assert.isTrue(UrlUtils.isValidRedirectUrl(forwardUrl),
                () -> "‘" + forwardUrl + "‘ is not a valid forward URL");
        this.forwardUrl = forwardUrl;
    }

    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
        request.getRequestDispatcher(forwardUrl).forward(request, response);
    }
}

处理异常信息

    /**
     * 失败
     *
     * @return
     */
    @RequestMapping("/failure")
    public String failure(HttpServletRequest request, Model model) {
        AuthenticationException exception = (AuthenticationException) request.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        String error;
        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
            error = "用户名或密码错误";
        } else if (exception instanceof DisabledException) {
            error = "账户已禁用";
        } else if (exception instanceof LockedException) {
            error = "账户已锁定";
        } else if (exception instanceof AccountExpiredException) {
            error = "账户已过期";
        } else if (exception instanceof CredentialsExpiredException) {
            error = "证书已过期";
        } else {
            error = "登录失败";
        }
        model.addAttribute("error", error);
        return "login";
    }

原文地址:https://www.cnblogs.com/yangchongxing/p/12304972.html

时间: 2024-07-29 18:24:32

【Spring Boot】Spring Security登陆异常出路的相关文章

Spring boot +Spring Security + Thymeleaf 认证失败返回错误信息

spring boot以其众多友谊的特性,如零配置.微服务等,吸引了很多的粉丝.而其与Spring Security安全框架的无缝结合,使其具备的安全的特性.在此基础上使用Thymeleaf模板引擎进行渲染,静动态结合,让页面开发更加简单.直观. 通过表单提交登录的用户名和密码是登录接口比较常见的一种设计.在初学的过程中,我也不例外的采用个这种方式.表单设计见下图. 登录成功,完成正常的主页面跳转,这个不存在问题.存在问题的是,登录失败了该咋办呢?我就在考虑,由于thymeleaf的局部刷新操作

Angular集成Spring Boot,Spring Security,JWT和CORS

本文介绍了Spring Boot的基本配置,Angular集成Spring Boot.Spring Security的方法.当前流行的JWT更适合与Angular集成,优于Spring Secuity提供的CSRF.另外引入了springfox-swagger和spring-boot-starter-actuator,演示了如何利用Swagger生成JSON API文档,如何利用Actuator监控应用. 本文前端基于Angular官方样例Tour of Heroes,请先到官网下载. 技术堆栈

255.Spring Boot+Spring Security:使用md5加密

说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)hibernate5.2.17.Final (6)MySQLDriver 5.1.47 (7)MySQL 8.0.12 需求缘起 很多时候,我们自己已经有现成的一套系统在运行了,这时候要接入spring security的话,那么难免会碰到一个问题:就是自己设计的密码加密方式和spring secur

256.Spring Boot+Spring Security: MD5是加密算法吗?

说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)hibernate5.2.17.Final (6)MySQLDriver 5.1.47 (7)MySQL 8.0.12 前言 有网友在公众号留言:准确的说md5是摘要算法不是加密算法 针对这个问题,当时也没有仔细的思考,空下来的时候,对于这个问题整理了下思路. 一.加密算法 1.1 加密和解密 1.1

Spring Boot/Spring Cloud、ESB、Dubbo

如何使用Spring Boot/Spring Cloud 实现微服务应用spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁.决策竞选.分布式会话和集群状态管理等操作提供了一种简单的开发方式. Spring Cloud与Dubbo对比提到Dubbo,我想顺便提下ESB,目前央视新华社也在用ESB来做任务编排,这里先比较下Dubbo和ESB: ESB(企业数据总线),一般采用集中式

Spring -&gt; Spring Boot &gt; Spring Cloud

Spring -> Spring Boot > Spring Cloud 这几天刚刚上班,公司用的是Spring Cloud,接触不多.我得赶快学起来. 想学习就必须得知道什么是微服务,什么是Spring Boot,什么是Spring Cloud,以及两者之间有什么关系? 什么是微服务? 简而言之,微服务架构风格是一种将单个应用程序作为一套小型服务开发的方法,每种应用程序都在自己的进程中运行,并与轻量级机制(通常是HTTP资源API)进行通信. 这些服务是围绕业务功能构建的,可以通过全自动部署

How to use JDBC-Authentication of Spring Boot/Spring Security with Flyway

java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) at org.springframework.test.context.suppo

Spring Boot 整合 Apache Solr 异常:Expected mime type application/octet-stream but got text/html 的解决.

解决方法:Spring Data Solr 3.0 以上版本 将@SolrDocument(solrCoreName = "new_core")  中的solrCoreName 字段改为使用collection字段即可 下面是问题解决经过: 暑假期间在做一个高并发的电商平台,需要用到Apache Solr. Solr 版本是7.4 , Spring Boot 版本是 2.0.4 , Spring Data Solr 为 3.0.9 网上大部分的教程用的版本比较旧,在实体类使用的都是  

215.Spring Boot+Spring Security:初体验

[视频&交流平台] SpringBoot视频:http://t.cn/R3QepWG Spring Cloud视频:http://t.cn/R3QeRZc SpringBoot Shiro视频:http://t.cn/R3QDMbh SpringBoot交流平台:http://t.cn/R3QDhU0 SpringData和JPA视频:http://t.cn/R1pSojf SpringSecurity5.0视频:http://t.cn/EwlLjHh 说明 (1)JDK版本:1.8 (2)Sp