zoukankan      html  css  js  c++  java
  • Spring Security 中如何让用户名不存在的错误显示出来(用户名不存在显示Bad credentials)

    默认情况下,不管你是用户名不存在,密码错误,SS都会报出Bad credentials异常信息,而不现实具体的错误。翻源码发现在org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider有如下这段代码。

    try { 
        user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication); 
    catch (UsernameNotFoundException notFound) { 
        logger.debug("User '" + username + "' not found"); 
     
        if (hideUserNotFoundExceptions) { 
            throw new BadCredentialsException(messages.getMessage( 
                    "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); 
        } else { 
            throw notFound; 
        } 
    }

    而该抽象类的hideUserNotFoundExceptions属性默认为false,所以默认就会隐藏掉用户名不存在的错误。

    网上有人说改源码,然后再打包编译,太暴力了,通过配置SS的applicationContext很容易修改这个属性。

    对于SS认证管理器,你原来可能是这么配置的:

    <security:authentication-manager alias="authenticationManager"> 
        <security:authentication-provider
            
    user-service-ref="customUserDetailsService" > 
        </security:authentication-provider> 
    </security:authentication-manager>

    刚才那个抽象类的一个实现类,org.springframework.security.authentication.dao.DaoAuthenticationProvider即是authentication-provider默认会使用的类,修改这部分如下:

    <security:authentication-manager alias="authenticationManager"> 
        <security:authentication-provider
            
    ref="authenticationProvider" > 
        </security:authentication-provider> 
    </security:authentication-manager> 
     
    <bean id="authenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> 
        <property name="userDetailsService" ref="customUserDetailsService" /> 
        <property name="hideUserNotFoundExceptions" value="false" /> 
    </bean>

    密码策略:

        <authentication-manager alias="MyAuthenticationManager">
            <authentication-provider ref="authenticationProvider" >
            </authentication-provider>
        </authentication-manager>
        
        <beans:bean id="authenticationProvider" 
            class
    ="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
            <beans:property name="userDetailsService" ref="userDetailService" />
            <!--显示用户错误信息-->
            <beans:property name="hideUserNotFoundExceptions" value="false" />
            <beans:property name="passwordEncoder" ref="UTPasswordEncoder" />
        </beans:bean>
  • 相关阅读:
    JSP基础语法
    《进化:从孤胆极客到高效团队》的目录
    什么是Webpack
    程序猿看市场
    mysql多表关联更新
    Nginx+Tomcat配置集群session共享
    DOUBLE精度问题,BigDecimal
    程序员是否该这样
    Spring上传文件报错
    Emoji表情符号录入MySQL数据库报错的解决方案
  • 原文地址:https://www.cnblogs.com/jifeng/p/2542928.html
Copyright © 2011-2022 走看看