Ich arbeite an Spring Boot, mit Frühling Sicherheit für Auth Login. Ich habe diesen Teil beendet. Jetzt möchte ich Captcha auf der Anmeldeseite implementieren. Ich habe es getan, aber manchmal ging der Wert schief. Hier mein Quellcode.Frühling Sicherheit validate captcha über Filter hat falschen Wert
Login-Seite
<form th:action="@{/j_spring_security_check}" method="post">
<tr>
<th align="left" width="30%">
<label for="userId">User Id</label>
</th>
<td width="70%">
<input type="text" style="width: 150px" name="userId" autocomplete="off"/>
</td>
</tr>
<tr>
<th align="left" width="30%">
Password
</th>
<td width="70%">
<input type="PASSWORD" style="width: 150px" name="password" autocomplete="off"/>
</td>
</tr>
<tr>
<th align="left" width="30%">
Answer
</th>
<td width="70%">
<input type="text" name="logonAnswer" style="width: 150px"/>
</td>
</tr>
<tr>
<td align="right">
</td>
<td align="left">
<div id="captcha"
style="cursor: pointer; height: 30px; width: 150px; display: inline-block; float: left"><img
th:src="@{/captcha}"/></div>
<div id="captchaRefresh" class="refresh-btn" title="Click to get other Captcha"></div>
</td>
</tr>
</form>
In Sicherheitskonfigurations
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Autowired
private RoleRepository roleRepository;
@Autowired
private CaptchaFilter captchaFilter;
@Autowired
private PasswordEncoder passwordEncoder() {
return new CustomerPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/register").permitAll()
.antMatchers("/configuration/**").hasRole(roleRepository.getRolesByGroup("USER"))
.antMatchers("/configuration/**", "/merchant/**", "/import/**", "/manualSettle/**", "/report/**", "/user/**").hasAnyRole(roleRepository.getRolesByGroup("ADMIN"))
.antMatchers("/superadmin").hasRole(roleRepository.getRolesByGroup("SUPERADMIN"))
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("userId")
.passwordParameter("password")
.defaultSuccessUrl("/")
.failureUrl("/login?error")
.and()
.addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
}
In captcha Validierfilter
@Autowired
UserDetailsServiceImpl userDetailsService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession(false);
if (userDetailsService != null
&& request.getParameter("logonAnswer") != null
&& !request.getParameter("logonAnswer").equals("")
&& session != null && request.getParameter("logonAnswer").equalsIgnoreCase(session.getAttribute("wirecardmposcaptcha").toString())) {
userDetailsService.setCaptchaOK(true);
}
chain.doFilter(request, response);
}
Und in userDetailsImplement
private boolean captchaOK;
public void setCaptchaOK(boolean captchaOK) {
this.captchaOK = captchaOK;
}
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Users user = userRepository.findByUserId(username);
if (user == null) {
throw new UsernameNotFoundException("UserId or Password invalid");
}
if (!captchaOK)
throw new InternalAuthenticationServiceException("Invalid Captcha");
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
Set<Roles> roles = user.getRoles();
for (Roles role : roles) {
grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName()));
}
return new org.springframework.security.core.userdetails.User(user.getUserId(), user.getPassword(), user.getEnabled().equals("true"), true, true, true, grantedAuthorities);
}
So in Login-Controller:
private String getErrorMessage(HttpServletRequest request, String key) {
Exception exception = (Exception) request.getSession().getAttribute(key);
String error = "";
if (exception instanceof BadCredentialsException) {
error = "Invalid user ID and password!";
} else if (exception instanceof DisabledException) {
error = "User is locked";
} else if (exception instanceof InternalAuthenticationServiceException) {
error = "Invalid answer.";
} else {
error = "Invalid user ID and password!";
}
return error;
}
Also, ich debuggen in captcha Filter der Wert captchaOk oft ändern. Nicht sicher, ob ich richtig mache.
Bitte werfen Sie einen Blick darauf und geben Sie Kommentare.
Danke.