Skip to content

Instantly share code, notes, and snippets.

@phuonghuynh
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phuonghuynh/857adec21c1cfd66b22a to your computer and use it in GitHub Desktop.
Save phuonghuynh/857adec21c1cfd66b22a to your computer and use it in GitHub Desktop.
Spring Security 4x support Web Socket
public class HttpSessionInitializer extends AbstractHttpSessionApplicationInitializer {
protected String getDispatcherWebApplicationContextSuffix() {
return AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME;
}
}
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableRedisHttpSession
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public EmbeddedRedisServer redisServer() {
return new EmbeddedRedisServer();
}
@Bean
public JedisConnectionFactory connectionFactory() throws Exception {
return new JedisConnectionFactory();
}
@Bean
public AuthenticationManager authenticationManager() {
return new SocialAuthenticationManager();
}
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().antMatchers("/user/**").hasAuthority("USER")
.and().formLogin().loginPage("/login").usernameParameter("key").successHandler(getSuccessHandler()).failureHandler(getAuthenticationFailureHandler())
.and().logout().logoutUrl("/logout").logoutSuccessHandler(getLogoutSuccessHandler()).invalidateHttpSession(true).deleteCookies("SESSION").permitAll()
.and().exceptionHandling().authenticationEntryPoint(getAuthenticationEntryPoint());
}
private AuthenticationEntryPoint getAuthenticationEntryPoint() {
return (request, response, authException) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
};
}
private LogoutSuccessHandler getLogoutSuccessHandler() {
return (request, response, authentication) -> {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
};
}
private AuthenticationFailureHandler getAuthenticationFailureHandler() {
return (request, response, exception) -> {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
};
}
private AuthenticationSuccessHandler getSuccessHandler() {
return (request, response, authentication) -> {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
};
}
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/images/**", "/css/**", "/generate-resources/**", "/modules/**", "/bower_components/**", "/custom-js/**");
}
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
protected String getDispatcherWebApplicationContextSuffix() {
return AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME;
}
}
public class SocialAuthenticationManager implements AuthenticationManager {
@Resource
private UserService userService;
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Unsupported authentication type");
Assert.isTrue(!authentication.isAuthenticated(), "Already authenticated");
String key = authentication.getPrincipal().toString();
if (!StringUtils.hasText(key)) {
throw new InternalAuthenticationServiceException("User key must not be empty.");
}
if (!Optional.ofNullable(userService.findUserEntityByKey(key)).isPresent()) {
throw new InternalAuthenticationServiceException("User does not exist in database.");
}
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(token.getPrincipal(), token.getPrincipal(), Arrays.asList(new SimpleGrantedAuthority("USER")));
return auth;
}
}
public class WebSocketSecurityConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages
.antMatchers("/user/**", "/queue/**", "/app/user/**").hasAuthority("USER");
}
}
@Stexxen
Copy link

Stexxen commented Feb 10, 2015

Most Helpful. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment