- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在使用 Spring boot + data rest 设置纯 json rest 服务,现在无法让我的自定义身份验证成功处理程序(以及身份验证失败处理程序)来处理登录响应。登录本身可以正常工作,但服务器响应状态为 302 的成功登录而没有重定向 url(这会触发错误,例如在 javascript 的 XMLHttpRequest 中)并完全忽略我在配置中设置的处理程序。
网络安全配置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private RESTAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private RESTAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private RESTAuthenticationSuccessHandler authenticationSuccessHandler;
@Autowired
private RESTLogoutSuccessHandler logoutSuccessHandler;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors();
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint);
http
.formLogin()
.permitAll()
.loginProcessingUrl("/login")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler);
http
.logout()
.permitAll()
.logoutUrl("/logout")
.logoutSuccessHandler(logoutSuccessHandler);
http
.sessionManagement()
.maximumSessions(1);
http.addFilterAt(getAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class);
http.authorizeRequests().anyRequest().authenticated();
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("*");
configuration.setAllowCredentials(true);
configuration.setExposedHeaders(Arrays.asList("X-CSRF-TOKEN"));
configuration.setAllowedHeaders(Arrays.asList("X-CSRF-TOKEN", "content-type"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));
configuration.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public PermissionEvaluator customPermissionEvaluator() {
return new CustomPermissionEvaluator();
}
protected CustomUsernamePasswordAuthenticationFilter getAuthenticationFilter() {
CustomUsernamePasswordAuthenticationFilter authFilter = new CustomUsernamePasswordAuthenticationFilter();
try {
authFilter.setAuthenticationManager(this.authenticationManagerBean());
} catch (Exception e) {
e.printStackTrace();
}
return authFilter;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
}
AuthenticationSuccessHandler:
@Component
public class RESTAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter writer = response.getWriter();
writer.write("Login OK");
writer.flush();
clearAuthenticationAttributes(request);
}
}
CustomUsernamePasswordAuthenticationFilter 只是从 json 中读取用户名和密码,它不会覆盖 filter() 方法:
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private boolean postOnly = true;
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
LoginRequest loginRequest;
try {
BufferedReader reader = request.getReader();
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line);
}
ObjectMapper mapper = new ObjectMapper();
loginRequest = mapper.readValue(sb.toString(), LoginRequest.class);
} catch (Exception ex) {
throw new AuthenticationServiceException("Unable to read login credentials.");
}
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
loginRequest.getEmail(), loginRequest.getPassword());
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
在调试日志中,我可以看到有一个奇怪的 RequestAwareAuthenticationSuccessHandler,它在登录处理程序之后获取请求,并且只是将默认重定向传递给“/”:
2016-12-28 15:44:02.358 DEBUG 6194 --- [nio-8080-exec-7] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2016-12-28 15:44:02.358 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [xxx.server.service.impl.UserDetailsServiceImpl.loadUserByUsername]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
2016-12-28 15:44:02.358 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@908810e] for JPA transaction
2016-12-28 15:44:02.358 DEBUG 6194 --- [nio-8080-exec-7] o.s.jdbc.datasource.DataSourceUtils : Setting JDBC Connection [ProxyConnection[PooledConnection[org.postgresql.jdbc.PgConnection@4d362a0f]]] read-only
2016-12-28 15:44:02.358 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC transaction [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@7cf6e5f]
[...]
2016-12-28 15:44:02.380 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
2016-12-28 15:44:02.380 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@908810e]
2016-12-28 15:44:02.381 DEBUG 6194 --- [nio-8080-exec-7] o.s.jdbc.datasource.DataSourceUtils : Resetting read-only flag of JDBC Connection [ProxyConnection[PooledConnection[org.postgresql.jdbc.PgConnection@4d362a0f]]]
2016-12-28 15:44:02.381 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@908810e] after transaction
2016-12-28 15:44:02.381 DEBUG 6194 --- [nio-8080-exec-7] o.s.orm.jpa.EntityManagerFactoryUtils : Closing JPA EntityManager
2016-12-28 15:44:02.488 DEBUG 6194 --- [nio-8080-exec-7] RequestAwareAuthenticationSuccessHandler : Using default Url: /
2016-12-28 15:44:02.488 DEBUG 6194 --- [nio-8080-exec-7] o.s.s.web.DefaultRedirectStrategy : Redirecting to '/'
2016-12-28 15:44:02.488 DEBUG 6194 --- [nio-8080-exec-7] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@273d8edd
2016-12-28 15:44:02.488 DEBUG 6194 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@faa222b9: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@faa222b9: Principal: org.springframework.security.core.userdetails.User@fa84ebb2: Username: hyriauser1@hyria-demo.tbd; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffed504: RemoteIpAddress: 127.0.0.1; SessionId: 1F3FF4A3203600AE56E3CB391BE96EFC; Granted Authorities: USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@692480d1
2016-12-28 15:44:02.488 DEBUG 6194 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
最佳答案
http
.formLogin()
.permitAll()
.loginProcessingUrl("/login")
.successHandler(authenticationSuccessHandler)
.failureHandler(authenticationFailureHandler);
您自己的 authenticationSuccessHandler
注入(inject)到 UsernamePasswordAuthenticationFilter
,并添加扩展 UsernamePasswordAuthenticationFilter
而不是 的
CustomUsernamePasswordAuthenticationFilter
用户名密码AuthenticationFilter
http.addFilterAt(getAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
但是您自己的 CustomUsernamePasswordAuthenticationFilter
使用默认的成功处理程序。
protected CustomUsernamePasswordAuthenticationFilter getAuthenticationFilter() {
CustomUsernamePasswordAuthenticationFilter authFilter = new CustomUsernamePasswordAuthenticationFilter();
try {
authFilter.setAuthenticationManager(this.authenticationManagerBean());
} catch (Exception e) {
e.printStackTrace();
}
return authFilter;
}
我看不到您将成功处理程序注入(inject) CustomUsernamePasswordAuthenticationFilter
的任何代码。
您需要将成功处理程序添加到 CustomUsernamePasswordAuthenticationFilter
。
authFilter.setAuthenticationManager(this.authenticationManagerBean());
// set handler
authFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
authFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
关于java - Spring Security 自定义 AuthenticationSuccessHandler 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41363596/
我刚刚在这个论坛的帮助下添加了一个 AuthenticationSuccessHandler,它在用户通过 fosuserbundle 或 fosfacebookbundle 登录时在我的网站上实现重
这是我的 AuthSuccessHandlerClass public class AuthSuccessHandler implements AuthenticationSuccessHandler
我正在使用 Spring MVC 网站并通过 LDAP 添加 Active Directory 身份验证。该公司不想使用 AD 权限来映射网站的权限,我们有一个列出每个用户权限的数据库,所以我试图连接
我实现了一个成功处理程序,如果用户是管理员用户,该处理程序会将用户重定向到特定页面。 public class MaunaKeaAuthenticationSuccessHandler impleme
我有一个使用 Spring 3.1 的 java webapp。我的 Spring 安全上下文定义了多个身份验证过滤器,每个过滤器对应一个不同的身份验证路径(例如,用户名/密码与单点登录)。每个身份验
我想为用户提供一种使用 token 登录的替代方法。我已经在 PreAuthenticationFilter 类中处理了对用户的身份验证,但是我需要触发我的 AuthenticationSuccess
你好 Stackoverflower, 我遇到了 Spring Security AuthenticationSuccessHandler 的问题。我实现了自定义 AuthenticationSucc
我在 Spring Boot 应用程序中使用了 Spring Security,有两种类型的用户:一种是 ADMIN,另一种只是普通用户。我从 DataSource 获取数据,然后执行 SQL 查询。
在其他一些帖子之后,我尝试覆盖 spring-security 处理程序的身份验证成功方法,但它从未被调用。我的代码如下所示: src/groovy/mypackage/MyAuthenticatio
在我的 Spring Security 应用程序中,我尝试在成功登录后返回 cookie 'remember_token'。我的 AuthenticanSuccessHandler 类自动连接 Rem
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 6 年前。 Improv
我有一个包含所有帐户信息的 Customer 类。(它不扩展 Spring 的 userdetails.User 类)我正在尝试在成功登录后做一些事情(例如设置新的上次登录时间)。为此,我设置了自定义
我想为我的登录过滤器实现自定义 AuthenticationSuccessHandler,即 org.springframework.security.web.authentication.remem
我正在使用 Spring boot + data rest 设置纯 json rest 服务,现在无法让我的自定义身份验证成功处理程序(以及身份验证失败处理程序)来处理登录响应。登录本身可以正常工作,
(编辑澄清)我有一个 POJO (SessionStorage) 来存储 session 特定数据,我想在成功验证后填充这些数据。由于我将 Scope 设置为“session”,我期望 MainCon
我是 Spring Security 3 的新手。我正在使用角色让用户登录。 我想根据用户的角色将用户重定向到不同的页面,我的理解是我必须为此实现 AuthenticationSuccessHandl
我有一个自定义的 AuthenticationSuccessHandler。 我想做的是在 onAuthenticationSuccess 方法中设置一些 session 数据。 为了存储 sessi
我有一个 Spring-MVC 应用程序(即我正在使用 Spring 的调度程序 servlet)。我还使用 Spring Security 来验证用户身份。由于我使用 Spring 的调度程序 se
我有三个角色,我想在登录后根据用户的角色将用户重定向到不同的页面。我知道这可以通过 AuthenticationSuccessHandler 来完成,但我在基于 Java 的配置中声明它时遇到了麻烦。
@Component("MyAuthFilter") public class MyAuthFilter extends UsernamePasswordAuthenticationF
我是一名优秀的程序员,十分优秀!