Skip to content

Instantly share code, notes, and snippets.

@thetekst
Created August 9, 2018 09:48
Show Gist options
  • Save thetekst/a5b37c6f3cf07bee85bf8ae1dd3f544c to your computer and use it in GitHub Desktop.
Save thetekst/a5b37c6f3cf07bee85bf8ae1dd3f544c to your computer and use it in GitHub Desktop.
Spring Boot 2 Security config auth
package ru.rtln.mailer.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import ru.rtln.mailer.rest.model.Response;
import ru.rtln.mailer.service.UserDetailsManager;
import ru.rtln.mailer.service.UserPrincipal;
import ru.rtln.mailer.service.exception.Errors;
import javax.servlet.http.HttpServletResponse;
/**
* Created by
*/
@Slf4j
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserDetailsManager userDetailsManager;
private final ObjectMapper objectMapper;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin().loginProcessingUrl("/login").usernameParameter("username").passwordParameter("password")
.successHandler((request, response, authentication) -> {
response.setStatus(HttpStatus.OK.value());
response.getWriter().write(objectMapper.writeValueAsString(Response.auth(Errors.OK,
((UserPrincipal) authentication.getPrincipal()))));
})
.failureHandler((request, response, exception) -> {
if (exception.getMessage().contains("Bad credentials")) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
log.info(exception.getMessage());
} else {
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
log.info(exception.getMessage());
}
})
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))
.logoutSuccessUrl("/login").deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.authenticationEntryPoint((request, response, authException) -> {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(objectMapper.writeValueAsString(authException.getMessage()));
log.info(authException.getMessage());
})
.and()
.authorizeRequests()
// .antMatchers("/templates/**").hasRole(Role.ADMIN.name())
.anyRequest().authenticated()
.requestMatchers(new AntPathRequestMatcher("/login"), new AntPathRequestMatcher("/event"))
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsManager).passwordEncoder(passwordEncoder());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment