Advertisement
Guest User

Untitled

a guest
Jun 24th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.91 KB | None | 0 0
  1. public class KBServicesAuthProvider implements AuthenticationProvider {
  2. @Autowired
  3. private ApplicationConfig applicationConfig;
  4.  
  5. @Autowired
  6. private SessionServiceClient sessionServiceClient;
  7.  
  8. @Override
  9. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  10. String email = (String) authentication.getPrincipal();
  11. String password = (String) authentication.getCredentials();
  12.  
  13. try {
  14. KBSessionInfo sessionInfo = sessionServiceClient.login(applicationConfig.getKbServicesPresenceId(), email,
  15. password);
  16.  
  17. List<GrantedAuthority> grantedRoles = new ArrayList<>();
  18. for (KBRoleMembership role : sessionInfo.getAuthenticatedUser().getRoleMemberships()) {
  19. grantedRoles.add(new SimpleGrantedAuthority(role.getRoleId()));
  20. }
  21.  
  22. return new UsernamePasswordAuthenticationToken(email, password, grantedRoles);
  23. } catch (InvalidSessionException e) {
  24. throw new AuthenticationCredentialsNotFoundException("Username or password was not accepted", e);
  25. }
  26. }
  27.  
  28. @Override
  29. public boolean supports(Class<?> authentication) {
  30. return authentication.equals(UsernamePasswordAuthenticationToken.class);
  31. }
  32. }
  33.  
  34. @Configuration
  35. @EnableWebMvcSecurity
  36. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  37.  
  38. @Autowired(required = true)
  39. SessionServiceClient sessionServiceClient;
  40.  
  41. @Override
  42. protected void configure(HttpSecurity http) throws Exception {
  43. http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated();
  44. http.formLogin().loginPage("/login").permitAll().and().logout().permitAll();
  45. }
  46.  
  47. @Override
  48. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  49. auth.authenticationProvider(getKBServicesAuthenticationProvider());
  50. }
  51.  
  52. @Bean
  53. protected AuthenticationProvider getKBServicesAuthenticationProvider() {
  54. return new KBServicesAuthProvider();
  55. }
  56. }
  57.  
  58. @Configuration
  59. @EnableWebMvcSecurity
  60. @EnableGlobalMethodSecurity(prePostEnabled = true)
  61. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  62.  
  63. @Autowired
  64. private CustomUserDetailsService userDetailsService;
  65. @Autowired
  66. private CustomAuthenticationProvider customAuthenticationProvider;
  67.  
  68. @Autowired
  69. public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
  70. auth.userDetailsService(userDetailsService);
  71. }
  72.  
  73. @Override
  74. protected void configure(HttpSecurity http) throws Exception {
  75. AuthenticationProvider rememberMeAuthenticationProvider = rememberMeAuthenticationProvider();
  76. TokenBasedRememberMeServices tokenBasedRememberMeServices = tokenBasedRememberMeServices();
  77.  
  78. List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(2);
  79. authenticationProviders.add(rememberMeAuthenticationProvider);
  80. authenticationProviders.add(customAuthenticationProvider);
  81. AuthenticationManager authenticationManager = authenticationManager(authenticationProviders);
  82.  
  83. http
  84. .csrf().disable()
  85. .headers().disable()
  86. .addFilter(new RememberMeAuthenticationFilter(authenticationManager, tokenBasedRememberMeServices))
  87. .rememberMe().rememberMeServices(tokenBasedRememberMeServices)
  88. .and()
  89. .authorizeRequests()
  90. .antMatchers("/js/**", "/css/**", "/img/**", "/login", "/processLogin").permitAll()
  91. .antMatchers("/index.jsp", "/index.html", "/index").hasRole("USER")
  92. .antMatchers("/admin", "/admin.html", "/admin.jsp", "/js/saic/jswe/admin/**").hasRole("ADMIN")
  93. .and()
  94. .formLogin().loginProcessingUrl("/processLogin").loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll()
  95. .and()
  96. .exceptionHandling().accessDeniedPage("/login")
  97. .and()
  98. .logout().permitAll();
  99. }
  100.  
  101. @Override
  102. public void configure(WebSecurity web) throws Exception {
  103. web.ignoring().antMatchers("/js/**", "/css/**", "/img/**");
  104. }
  105.  
  106. @Bean
  107. public BCryptPasswordEncoder bCryptPasswordEncoder(){
  108. return new BCryptPasswordEncoder();
  109. }
  110.  
  111. @Bean
  112. public AuthenticationManager authenticationManager(List<AuthenticationProvider> authenticationProviders) {
  113. return new ProviderManager(authenticationProviders);
  114. }
  115.  
  116. @Bean
  117. public TokenBasedRememberMeServices tokenBasedRememberMeServices() {
  118. return new TokenBasedRememberMeServices("testKey", userDetailsService);
  119. }
  120.  
  121. @Bean
  122. public AuthenticationProvider rememberMeAuthenticationProvider() {
  123. return new org.springframework.security.authentication.RememberMeAuthenticationProvider("testKey");
  124. }
  125.  
  126. protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
  127. auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
  128. }
  129. }
  130.  
  131. http
  132. .csrf().disable()
  133. .headers().disable()
  134. .authenticationProvider(customAuthenticationProvider)
  135.  
  136. @Override
  137. public boolean supports(Class<?> authentication) {
  138. return authentication.equals
  139. (UsernamePasswordAuthenticationToken.class);
  140. }
  141.  
  142. @Override
  143. public boolean supports(Class<?> authentication) {
  144. return (UsernamePasswordAuthenticationToken.class
  145. .isAssignableFrom(authentication));
  146. }
  147.  
  148. @Autowired
  149. @Override
  150. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  151. auth.authenticationProvider(getKBServicesAuthenticationProvider());
  152. }
  153.  
  154. @Override
  155. protected void configure(HttpSecurity http) throws Exception {
  156. http.authorizeRequests().anyRequest().authenticated();
  157. http.formLogin().loginPage("/login").permitAll().and().logout().permitAll();
  158. }
  159.  
  160. public class Application {
  161. public static void main( String[] args ) {
  162. SpringApplication.run(new Class[] {AppConfig.class, Initializer.class, SecurityInitializer.class}, args);
  163. }
  164. }
  165.  
  166. public class Initializer extends SpringBootServletInitializer implements WebApplicationInitializer {
  167.  
  168. @Override
  169. protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
  170. return application.sources(AppConfig.class);
  171. }
  172.  
  173. @Override
  174. public void onStartup(ServletContext container) throws ServletException {
  175. AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  176. rootContext.register(AppConfig.class);
  177.  
  178. // Manage the lifecycle of the root application context
  179. container.addListener(new ContextLoaderListener(rootContext));
  180.  
  181. // Create the dispatcher servlet's Spring application context
  182. AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  183. dispatcherContext.register(WebConfig.class);
  184.  
  185. // Register and map the dispatcher servlet
  186. ServletRegistration.Dynamic dispatcher = container.addServlet("my-servlet", new DispatcherServlet(dispatcherContext));
  187. dispatcher.setLoadOnStartup(1);
  188. dispatcher.addMapping("/*");
  189. }
  190. }
  191.  
  192. public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
  193.  
  194. }
  195.  
  196. @Configuration
  197. @EnableAutoConfiguration
  198. @EnableScheduling
  199. @EnableMBeanExport
  200. @EnableAsync
  201. @EnableAspectJAutoProxy
  202. @ComponentScan("com.my.package")
  203. public class AppConfig {
  204.  
  205.  
  206. }
  207.  
  208. @Configuration
  209. @EnableWebSecurity
  210. @ComponentScan("com.my.package")
  211. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  212.  
  213. @Autowired
  214. private RestfulRemoteAuthenticationProvider restfulRemoteAuthenticationProvider;
  215.  
  216. @Override
  217. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  218. auth.authenticationProvider(restfulRemoteAuthenticationProvider);
  219. }
  220.  
  221. @Override
  222. protected void configure(HttpSecurity http) throws Exception {
  223. http.csrf().disable();
  224. http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
  225. }
  226. }
  227.  
  228. @Configuration
  229. @EnableWebMvc
  230. @ComponentScan(basePackages = "com.my.controller.package")
  231. public class WebConfig extends WebMvcConfigurerAdapter {
  232.  
  233. @Bean
  234. public InternalResourceViewResolver internalViewResolver() {
  235. InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
  236. viewResolver.setPrefix("/WEB-INF/jsp/");
  237. viewResolver.setSuffix(".jsp");
  238. viewResolver.setOrder(1);
  239. return viewResolver;
  240. }
  241. }
  242.  
  243. @Component
  244. public class RestfulRemoteAuthenticationProvider implements AuthenticationProvider {
  245.  
  246. @Autowired
  247. private ManagementClientAdapterFactory managementClientAdapterFactory;
  248.  
  249. @Override
  250. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  251. String username = authentication.getName();
  252. String password = authentication.getCredentials().toString();
  253.  
  254. // my logic to get and configure authSource which is my environment specific thing, also same for RemoteAuthRequestResult
  255.  
  256. RemoteAuthRequestResult result = (RemoteAuthRequestResult)authSource.sendRequest();
  257. if(result.isAuthenticated()) {
  258. List<GrantedAuthority> grantedAuths = new ArrayList<>();
  259. grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
  260. return new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
  261. }
  262. throw new BadCredentialsException("User not found by given credential");
  263. }
  264.  
  265. @Override
  266. public boolean supports(Class<?> authentication) {
  267. return authentication.equals(UsernamePasswordAuthenticationToken.class);
  268. }
  269. }
  270.  
  271. Something like should be present in java config
  272. @Configuration
  273. @EnableGlobalMethodSecurity(prePostEnabled=true)
  274. public class HelloMethodSecurityConfig {
  275. }
  276.  
  277. <security:global-method-security pre-post-annotations="enabled"/>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement