Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class KBServicesAuthProvider implements AuthenticationProvider {
- @Autowired
- private ApplicationConfig applicationConfig;
- @Autowired
- private SessionServiceClient sessionServiceClient;
- @Override
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- String email = (String) authentication.getPrincipal();
- String password = (String) authentication.getCredentials();
- try {
- KBSessionInfo sessionInfo = sessionServiceClient.login(applicationConfig.getKbServicesPresenceId(), email,
- password);
- List<GrantedAuthority> grantedRoles = new ArrayList<>();
- for (KBRoleMembership role : sessionInfo.getAuthenticatedUser().getRoleMemberships()) {
- grantedRoles.add(new SimpleGrantedAuthority(role.getRoleId()));
- }
- return new UsernamePasswordAuthenticationToken(email, password, grantedRoles);
- } catch (InvalidSessionException e) {
- throw new AuthenticationCredentialsNotFoundException("Username or password was not accepted", e);
- }
- }
- @Override
- public boolean supports(Class<?> authentication) {
- return authentication.equals(UsernamePasswordAuthenticationToken.class);
- }
- }
- @Configuration
- @EnableWebMvcSecurity
- public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired(required = true)
- SessionServiceClient sessionServiceClient;
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated();
- http.formLogin().loginPage("/login").permitAll().and().logout().permitAll();
- }
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.authenticationProvider(getKBServicesAuthenticationProvider());
- }
- @Bean
- protected AuthenticationProvider getKBServicesAuthenticationProvider() {
- return new KBServicesAuthProvider();
- }
- }
- @Configuration
- @EnableWebMvcSecurity
- @EnableGlobalMethodSecurity(prePostEnabled = true)
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired
- private CustomUserDetailsService userDetailsService;
- @Autowired
- private CustomAuthenticationProvider customAuthenticationProvider;
- @Autowired
- public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService);
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- AuthenticationProvider rememberMeAuthenticationProvider = rememberMeAuthenticationProvider();
- TokenBasedRememberMeServices tokenBasedRememberMeServices = tokenBasedRememberMeServices();
- List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(2);
- authenticationProviders.add(rememberMeAuthenticationProvider);
- authenticationProviders.add(customAuthenticationProvider);
- AuthenticationManager authenticationManager = authenticationManager(authenticationProviders);
- http
- .csrf().disable()
- .headers().disable()
- .addFilter(new RememberMeAuthenticationFilter(authenticationManager, tokenBasedRememberMeServices))
- .rememberMe().rememberMeServices(tokenBasedRememberMeServices)
- .and()
- .authorizeRequests()
- .antMatchers("/js/**", "/css/**", "/img/**", "/login", "/processLogin").permitAll()
- .antMatchers("/index.jsp", "/index.html", "/index").hasRole("USER")
- .antMatchers("/admin", "/admin.html", "/admin.jsp", "/js/saic/jswe/admin/**").hasRole("ADMIN")
- .and()
- .formLogin().loginProcessingUrl("/processLogin").loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll()
- .and()
- .exceptionHandling().accessDeniedPage("/login")
- .and()
- .logout().permitAll();
- }
- @Override
- public void configure(WebSecurity web) throws Exception {
- web.ignoring().antMatchers("/js/**", "/css/**", "/img/**");
- }
- @Bean
- public BCryptPasswordEncoder bCryptPasswordEncoder(){
- return new BCryptPasswordEncoder();
- }
- @Bean
- public AuthenticationManager authenticationManager(List<AuthenticationProvider> authenticationProviders) {
- return new ProviderManager(authenticationProviders);
- }
- @Bean
- public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
- return new TokenBasedRememberMeServices("testKey", userDetailsService);
- }
- @Bean
- public AuthenticationProvider rememberMeAuthenticationProvider() {
- return new org.springframework.security.authentication.RememberMeAuthenticationProvider("testKey");
- }
- protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
- }
- }
- http
- .csrf().disable()
- .headers().disable()
- .authenticationProvider(customAuthenticationProvider)
- @Override
- public boolean supports(Class<?> authentication) {
- return authentication.equals
- (UsernamePasswordAuthenticationToken.class);
- }
- @Override
- public boolean supports(Class<?> authentication) {
- return (UsernamePasswordAuthenticationToken.class
- .isAssignableFrom(authentication));
- }
- @Autowired
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.authenticationProvider(getKBServicesAuthenticationProvider());
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.authorizeRequests().anyRequest().authenticated();
- http.formLogin().loginPage("/login").permitAll().and().logout().permitAll();
- }
- public class Application {
- public static void main( String[] args ) {
- SpringApplication.run(new Class[] {AppConfig.class, Initializer.class, SecurityInitializer.class}, args);
- }
- }
- public class Initializer extends SpringBootServletInitializer implements WebApplicationInitializer {
- @Override
- protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
- return application.sources(AppConfig.class);
- }
- @Override
- public void onStartup(ServletContext container) throws ServletException {
- AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
- rootContext.register(AppConfig.class);
- // Manage the lifecycle of the root application context
- container.addListener(new ContextLoaderListener(rootContext));
- // Create the dispatcher servlet's Spring application context
- AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
- dispatcherContext.register(WebConfig.class);
- // Register and map the dispatcher servlet
- ServletRegistration.Dynamic dispatcher = container.addServlet("my-servlet", new DispatcherServlet(dispatcherContext));
- dispatcher.setLoadOnStartup(1);
- dispatcher.addMapping("/*");
- }
- }
- public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
- }
- @Configuration
- @EnableAutoConfiguration
- @EnableScheduling
- @EnableMBeanExport
- @EnableAsync
- @EnableAspectJAutoProxy
- @ComponentScan("com.my.package")
- public class AppConfig {
- }
- @Configuration
- @EnableWebSecurity
- @ComponentScan("com.my.package")
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
- @Autowired
- private RestfulRemoteAuthenticationProvider restfulRemoteAuthenticationProvider;
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.authenticationProvider(restfulRemoteAuthenticationProvider);
- }
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http.csrf().disable();
- http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
- }
- }
- @Configuration
- @EnableWebMvc
- @ComponentScan(basePackages = "com.my.controller.package")
- public class WebConfig extends WebMvcConfigurerAdapter {
- @Bean
- public InternalResourceViewResolver internalViewResolver() {
- InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
- viewResolver.setPrefix("/WEB-INF/jsp/");
- viewResolver.setSuffix(".jsp");
- viewResolver.setOrder(1);
- return viewResolver;
- }
- }
- @Component
- public class RestfulRemoteAuthenticationProvider implements AuthenticationProvider {
- @Autowired
- private ManagementClientAdapterFactory managementClientAdapterFactory;
- @Override
- public Authentication authenticate(Authentication authentication) throws AuthenticationException {
- String username = authentication.getName();
- String password = authentication.getCredentials().toString();
- // my logic to get and configure authSource which is my environment specific thing, also same for RemoteAuthRequestResult
- RemoteAuthRequestResult result = (RemoteAuthRequestResult)authSource.sendRequest();
- if(result.isAuthenticated()) {
- List<GrantedAuthority> grantedAuths = new ArrayList<>();
- grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
- return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
- }
- throw new BadCredentialsException("User not found by given credential");
- }
- @Override
- public boolean supports(Class<?> authentication) {
- return authentication.equals(UsernamePasswordAuthenticationToken.class);
- }
- }
- Something like should be present in java config
- @Configuration
- @EnableGlobalMethodSecurity(prePostEnabled=true)
- public class HelloMethodSecurityConfig {
- }
- <security:global-method-security pre-post-annotations="enabled"/>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement