Используя Spring Security, я могу проверить, правильно ли введено пользователем имя пользователя / пароль или нет.В случае неудачи мне нужно точно определить причину, потому что имя пользователя или пароль или оба, чтобы вернуть сообщение соответственно.
Мой текущий код всегда возвращает мне ошибку 401 с сообщением Bad Credentials
всякий раз, когда происходит сбойв процессе аутентификации.Я хочу, чтобы пользовательский код возвращался как Wrong username
при неправильном имени пользователя или Wrong password
при неверном пароле.
Я определил пользовательский фильтр и точку входа для аутентификации для приложения.
public class JWTUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
....
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
password, Collections.emptyList());
return authenticationManager.authenticate(authenticationToken);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException failed) throws IOException, ServletException {
String username = request.getParameter("username");
try {
// Do some process stuff....
} catch (Exception ex) {
log.error(ex);
}
super.unsuccessfulAuthentication(request, response, failed);
}
}
Конфигурационный класс
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationExceptionEntryPoint authenticationEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().cacheControl();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.csrf().disable();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
.addFilter(new JWTUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, userService, accessHistoryService))
.addFilter(new JwtAuthorizationFilter(authenticationManager(), jwtConfig)).authorizeRequests();
http.authorizeRequests().antMatchers(HttpMethod.POST, jwtConfig.getUri()).permitAll()
.antMatchers("/auth/**").permitAll()
.antMatchers("/1/**").hasRole(RoleConstant.ROLE_ADMIN)
.antMatchers("/test/**").hasAnyRole(RoleConstant.ROLE_ADMIN)
.antMatchers("/report/**").hasAnyRole(RoleConstant.ROLE_ADMIN, RoleConstant.ROLE_REPORT)
.anyRequest().authenticated();
// If a user try to access a resource without having enough permissions
http.exceptionHandling().accessDeniedPage("/login");
//test in browser
http.httpBasic();
}
}