当前位置: 首页 > 知识库问答 >
问题:

Spring Boot Security OAuth2自定义异常消息

毛弘博
2023-03-14

我在spring boot RESTfull项目中有一些特殊情况,而不是标准的自定义身份验证异常时的错误消息。我需要一个不同的消息取决于用户名或密码是错误的,或者如果用户名不存在,或者如果用户在数据库中被停用。目前我只能得到消息“bad credentials”,我还没有找到任何解决方案,如何根据用户属性或特殊情况自定义消息。

我当前有如下自定义身份验证提供程序:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws org.springframework.security.core.AuthenticationException {


        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        UserDetails userDetails = userDetailsService.loadUserByUsername(name);


        if(passwordEncoder.matches(password, userDetails.getPassword())) {
            return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),
                    userDetails.getAuthorities());
        }

        return null;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }


}

我有这样的定制用户详细信息服务:

@Service
public class CustomUserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService{

    @Autowired
    UserService userService; //my custom user service

    @Override
    public UserDetails loadUserByUsername(String username) {
        try {
            User user = userService.getUserByUsername(username);

            if(user == null) {
                throw new UsernameNotFoundException("Username doesn't exist");
            } else if(user.isDeactivated()) {
                throw new UsernameNotFoundException("User deactivated");
            }

            List<Authority> listOfAuthorities = userService.getAllAuthoritiesFromUser(user.getUserId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

            for(Authority authority : listOfAuthorities) {
                grantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));
            }

            org.springframework.security.core.userdetails.User userNew =
            new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
            return userNew;

        }
        catch(Exception ex) {
            throw new UsernameNotFoundException("Username or password not correct");
        }

    }
}

在哪里可以处理来自Throw new UsernameNotFoundException的消息,并将其作为“error_description”返回?

编辑此处也是我的SecurityConfigResourceServerConfig:

@Configuration
@EnableWebSecurity
@Order(Ordered.LOWEST_PRECEDENCE)
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    CustomUserDetailsService userDetailsService;

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider)  
        .userDetailsService(userDetailsService)
        .passwordEncoder(passwordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.addFilterBefore(new AuthenticationTokenFilter(authenticationManager()), BasicAuthenticationFilter.class);
    }

    // must be overriden and exposed as @Bean, otherwise boot's AuthenticationManagerConfiguration will take precedence
    @Bean @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{

    @Autowired
    private AuthExceptionEntryPoint myEntryPoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.anonymous().and().authorizeRequests().antMatchers("/**")
                .authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(myEntryPoint).accessDeniedHandler(new OAuth2AccessDeniedHandler());
    }

}

共有1个答案

隆兴修
2023-03-14

这个关于Spring Security的通用消息是有目的的,它是为了混淆登录失败的实际原因。

一旦根据需要提供特定消息,例如用户名不存在用户停用密码不正确等等,就会开始为恶意用户提供过多的信息。

更新

public class DefaultAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, 
                                            AuthenticationException exception) throws IOException, ServletException {
            super.onAuthenticationFailure(request, response, exception);
            if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
                response.sendRedirect("User not found")
            } else if (exception.getClass().isAssignableFrom(LockedException.class)) {
                response.sendRedirect("User Locked")
            }
        }
    }
 类似资料:
  • 如果 Java 提供的内置异常类型不能满足程序设计的需求,这时我们可以自己设计 Java 类库或框架,其中包括异常类型。实现自定义异常类需要继承 Exception 类或其子类,如果自定义运行时异常类需继承 RuntimeException 类或其子类。 自定义异常的语法形式为: 在编码规范上,一般将自定义异常类的类名命名为 XXXException,其中 XXX 用来代表该异常的作用。 自定义异

  • 我是一名Java编程新手(实际上已经在学习),我对如何处理不同的消息有些怀疑。 我的目标是将这些不同的消息包含在同一个类(CustomExcpse类)中,以避免在从其他类抛出新CustomExceptions的每个方法上一遍又一遍地编写相同的字符串。 到目前为止,我编码: > 一个自定义异常类,它从异常扩展而来,具有不同的消息(在示例中只有两个,但还有更多)作为Strings包含,当然还有构造函数

  • 我使用的是JBossAS7。我已经知道如何使用自己的错误页处理HTTP错误(例如404、500、...)--这不是问题。但出于调试的原因,我需要查看错误stacktrace。如何访问默认显示的消息并将其嵌入到错误页面中?

  • 我正在尝试使用Spring Boot 2.1给出的验证JWT令牌内的声明。问题是Spring总是使用默认异常消息抛出异常: 即使我创建了一个扩展ClientAuthenticationException的自定义异常,我也会收到相同的异常消息。 当JWT声明验证失败时,我想修改异常消息。这是我的配置类: 这是我的JWTClaimVerifier类: 当JWT声明验证失败时,我希望我的自定义异常消息有

  • 我希望捕捉一些jackson异常,这些异常发生在我正在开发的spring-boot API中。例如,我有下面的request类,我想捕获当JSON request对象中的“QuarmissionAireResponse”键为null或空白(即request对象中的)时发生的错误。 导致此Jackson错误: 是否有一种方法来捕获和处理这些异常(在示例中JsonRootName是null/inval

  • 我有一个Spring Security保护的Spring Boot应用程序。一切都很好。但如果用户帐户被锁定,我如何将消息显示为account locked,而不是Invalid user name and password。 我的登录表单 安全配置