List of usage examples for org.springframework.security.web.util.matcher RequestMatcher RequestMatcher
RequestMatcher
From source file:eu.eidas.sp.CsrfSecurityConfig.java
@Override protected void configure(HttpSecurity http) throws Exception { // Build the request matcher for CSFR protection RequestMatcher csrfRequestMatcher = new RequestMatcher() { // Disable CSFR protection on the following urls: private AntPathRequestMatcher[] requestMatchers = { new AntPathRequestMatcher("/respeidas", "POST"), new AntPathRequestMatcher("/mdeidas", "GET") }; @Override/*w w w .ja v a2 s. co m*/ public boolean matches(HttpServletRequest request) { // If the request match one url the CSFR protection will be disabled for (AntPathRequestMatcher rm : requestMatchers) { if (rm.matches(request)) { return false; } } return true; } // method matches }; // new RequestMatcher // Set security configurations http // Disable the csrf protection on some request matches .csrf().disable(); //.requireCsrfProtectionMatcher(csrfRequestMatcher).and(); }
From source file:com.erudika.para.security.OpenIDAuthFilter.java
/** * Default constructor./*from w w w .j av a2 s.c o m*/ * @param defaultFilterProcessesUrl the url of the filter */ public OpenIDAuthFilter(final String defaultFilterProcessesUrl) { setRequiresAuthenticationRequestMatcher(new RequestMatcher() { public boolean matches(HttpServletRequest request) { String uri = request.getRequestURI(); boolean matches; if ("".equals(request.getContextPath())) { matches = uri.endsWith(defaultFilterProcessesUrl); } else { matches = uri.endsWith(request.getContextPath() + defaultFilterProcessesUrl); } return matches; } }); }
From source file:com.orange.clara.tool.config.SecurityConfig.java
@Override protected void configure(HttpSecurity http) throws Exception { http.requestMatcher(new RequestMatcher() { @Override// w w w. j a v a2 s . c o m public boolean matches(HttpServletRequest httpServletRequest) { return httpServletRequest.getHeader("Authorization") == null; } }).authorizeRequests().antMatchers("/api/admin/**").hasRole(UserRole.ADMIN) .antMatchers("/info/**", "/ws/**").permitAll().anyRequest().authenticated().and().csrf() .csrfTokenRepository(csrfTokenRepository()).and() .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class); if (useSsl) { http.requiresChannel().anyRequest().requiresSecure(); } }
From source file:com.erudika.para.security.SecurityConfig.java
/** * Configures the protected private resources * * @param http HTTP sec object//from ww w .j av a 2 s . c om * @throws Exception ex */ @Override protected void configure(HttpSecurity http) throws Exception { String[] defRoles = { "USER", "MOD", "ADMIN" }; Map<String, String> confMap = Config.getConfigMap(); ConfigObject c = Config.getConfig().getObject("security.protected"); ConfigValue apiSec = Config.getConfig().getValue("security.api_security"); boolean enableRestFilter = apiSec != null && Boolean.TRUE.equals(apiSec.unwrapped()); for (String key : c.keySet()) { ConfigValue cv = c.get(key); ArrayList<String> patterns = new ArrayList<String>(); ArrayList<String> roles = new ArrayList<String>(); // if API security is disabled don't add any API related patterns // to the list of protected resources if (!"api".equals(key) || enableRestFilter) { for (ConfigValue configValue : (ConfigList) cv) { if (configValue instanceof List) { for (ConfigValue role : (ConfigList) configValue) { roles.add(((String) role.unwrapped()).toUpperCase()); } } else { patterns.add((String) configValue.unwrapped()); } } String[] rolz = (roles.isEmpty()) ? defRoles : roles.toArray(new String[0]); http.authorizeRequests().antMatchers(patterns.toArray(new String[0])).hasAnyRole(rolz); } } if (Config.getConfigParamUnwrapped("security.csrf_protection", true)) { CachedCsrfTokenRepository str = new CachedCsrfTokenRepository(); Para.injectInto(str); http.csrf().requireCsrfProtectionMatcher(new RequestMatcher() { private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$"); private final RegexRequestMatcher authEndpoints = new RegexRequestMatcher("^/\\w+_auth$", null); public boolean matches(HttpServletRequest request) { boolean matches = !RestRequestMatcher.INSTANCE.matches(request) && !IgnoredRequestMatcher.INSTANCE.matches(request) && !authEndpoints.matches(request) && !allowedMethods.matcher(request.getMethod()).matches(); return matches; } }).csrfTokenRepository(str); } else { http.csrf().disable(); } http.sessionManagement().enableSessionUrlRewriting(false); http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER); http.sessionManagement().sessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy()); http.exceptionHandling() .authenticationEntryPoint(new SimpleAuthenticationEntryPoint(confMap.get("security.signin"))); http.exceptionHandling() .accessDeniedHandler(new SimpleAccessDeniedHandler(confMap.get("security.access_denied"))); http.requestCache().requestCache(new SimpleRequestCache()); http.logout().logoutUrl(confMap.get("security.signout")) .logoutSuccessUrl(confMap.get("security.signout_success")); SimpleAuthenticationSuccessHandler successHandler = new SimpleAuthenticationSuccessHandler(); successHandler.setDefaultTargetUrl(confMap.get("security.signin_success")); successHandler.setTargetUrlParameter(confMap.get("security.returnto")); successHandler.setUseReferer(true); SimpleAuthenticationFailureHandler failureHandler = new SimpleAuthenticationFailureHandler(); failureHandler.setDefaultFailureUrl(confMap.get("security.signin_failure")); SimpleRememberMeServices tbrms = new SimpleRememberMeServices(Config.APP_SECRET_KEY, new SimpleUserService()); tbrms.setAlwaysRemember(true); tbrms.setTokenValiditySeconds(Config.SESSION_TIMEOUT_SEC.intValue()); tbrms.setCookieName(Config.AUTH_COOKIE); tbrms.setParameter(Config.AUTH_COOKIE.concat("-remember-me")); http.rememberMe().rememberMeServices(tbrms); PasswordAuthFilter passwordFilter = new PasswordAuthFilter("/" + PasswordAuthFilter.PASSWORD_ACTION); passwordFilter.setAuthenticationManager(authenticationManager()); passwordFilter.setAuthenticationSuccessHandler(successHandler); passwordFilter.setAuthenticationFailureHandler(failureHandler); passwordFilter.setRememberMeServices(tbrms); OpenIDAuthFilter openidFilter = new OpenIDAuthFilter("/" + OpenIDAuthFilter.OPENID_ACTION); openidFilter.setAuthenticationManager(authenticationManager()); openidFilter.setConsumer(new OpenID4JavaConsumer(new SimpleAxFetchListFactory())); openidFilter.setReturnToUrlParameters(Collections.singleton(confMap.get("security.returnto"))); openidFilter.setAuthenticationSuccessHandler(successHandler); openidFilter.setAuthenticationFailureHandler(failureHandler); openidFilter.setRememberMeServices(tbrms); FacebookAuthFilter facebookFilter = new FacebookAuthFilter("/" + FacebookAuthFilter.FACEBOOK_ACTION); facebookFilter.setAuthenticationManager(authenticationManager()); facebookFilter.setAuthenticationSuccessHandler(successHandler); facebookFilter.setAuthenticationFailureHandler(failureHandler); facebookFilter.setRememberMeServices(tbrms); GoogleAuthFilter googleFilter = new GoogleAuthFilter("/" + GoogleAuthFilter.GOOGLE_ACTION); googleFilter.setAuthenticationManager(authenticationManager()); googleFilter.setAuthenticationSuccessHandler(successHandler); googleFilter.setAuthenticationFailureHandler(failureHandler); googleFilter.setRememberMeServices(tbrms); LinkedInAuthFilter linkedinFilter = new LinkedInAuthFilter("/" + LinkedInAuthFilter.LINKEDIN_ACTION); linkedinFilter.setAuthenticationManager(authenticationManager()); linkedinFilter.setAuthenticationSuccessHandler(successHandler); linkedinFilter.setAuthenticationFailureHandler(failureHandler); linkedinFilter.setRememberMeServices(tbrms); TwitterAuthFilter twitterFilter = new TwitterAuthFilter("/" + TwitterAuthFilter.TWITTER_ACTION); twitterFilter.setAuthenticationManager(authenticationManager()); twitterFilter.setAuthenticationSuccessHandler(successHandler); twitterFilter.setAuthenticationFailureHandler(failureHandler); twitterFilter.setRememberMeServices(tbrms); GitHubAuthFilter githubFilter = new GitHubAuthFilter("/" + GitHubAuthFilter.GITHUB_ACTION); githubFilter.setAuthenticationManager(authenticationManager()); githubFilter.setAuthenticationSuccessHandler(successHandler); githubFilter.setAuthenticationFailureHandler(failureHandler); githubFilter.setRememberMeServices(tbrms); http.addFilterAfter(passwordFilter, BasicAuthenticationFilter.class); http.addFilterAfter(openidFilter, BasicAuthenticationFilter.class); http.addFilterAfter(facebookFilter, BasicAuthenticationFilter.class); http.addFilterAfter(googleFilter, BasicAuthenticationFilter.class); http.addFilterAfter(linkedinFilter, BasicAuthenticationFilter.class); http.addFilterAfter(twitterFilter, BasicAuthenticationFilter.class); http.addFilterAfter(githubFilter, BasicAuthenticationFilter.class); if (enableRestFilter) { RestAuthFilter restFilter = new RestAuthFilter(new Signer()); http.addFilterAfter(restFilter, RememberMeAuthenticationFilter.class); } }
From source file:architecture.user.spring.config.SecurityConfig.java
@Bean(name = "nonAjaxRequestMatcher") public RequestMatcher nonAjaxRequestMatcher() { return new RequestMatcher() { @Override/*from w w w . j av a 2s . c o m*/ public boolean matches(HttpServletRequest request) { if (!"XmlHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"))) { return true; } OutputFormat format = OutputFormat .stingToOutputFormat(StringUtils.defaultString(request.getParameter("output"), "html")); if (format == OutputFormat.HTML) return true; return false; } }; }
From source file:de.hska.ld.core.config.security.openidconnect.OIDCSecurityConfig.java
@Override @SuppressWarnings("unchecked") protected void configure(HttpSecurity http) throws Exception { OIDCAuthenticationFilter oidcFilter = openIdConnectAuthenticationFilter(); oidcFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() { @Override/*from www.j av a 2 s .co m*/ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.sendRedirect(env.getProperty("module.core.oidc.redirect.to.client")); } }); oidcFilter.setApplicationEventPublisher(new ApplicationEventPublisher() { @Override public void publishEvent(ApplicationEvent event) { Object source = event.getSource(); OIDCAuthenticationToken token = null; if (source != null) { token = (OIDCAuthenticationToken) source; } if (token != null) { Map map = (Map) token.getPrincipal(); Iterator iterator = map.entrySet().iterator(); String subId = null; String issuer = null; if (iterator.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next(); if ("sub".equals(entry.getKey())) { // check if sub id is already present in the database subId = entry.getValue(); if (subId == null) { throw new UnsupportedOperationException("No subId found!"); } } } if (iterator.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next(); if ("iss".equals(entry.getKey())) { issuer = entry.getValue(); if (!env.getProperty("module.core.oidc.identity.provider.url").equals(issuer)) { throw new UnsupportedOperationException("Wrong or no issuer found!"); } } } User currentUserInDb = userService.findBySubIdAndIssuer(subId, issuer); UserInfo oidcUserInfo = ((OIDCAuthenticationToken) source).getUserInfo(); if (currentUserInDb == null && oidcUserInfo != null) { User savedUser = createNewUserFirstLogin(token, subId, issuer, oidcUserInfo); try { userEventsPublisher.sendUserLoginEvent(savedUser); userEventsPublisher.sendUserFirstLoginEvent(savedUser); } catch (Exception e) { // } LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail())); Logger.trace("User logs in for the first time."); LoggingContext.clear(); } else if (oidcUserInfo != null) { User savedUser = updateUserInformationFromOIDC(token, currentUserInDb, oidcUserInfo); try { userEventsPublisher.sendUserLoginEvent(savedUser); } catch (Exception e) { // } LoggingContext.put("user_email", EscapeUtil.escapeJsonForLogging(savedUser.getEmail())); Logger.trace("User logs in."); LoggingContext.clear(); } else { // oidc information is null throw new UnsupportedOperationException("No OIDC information found!"); } } } private User updateUserInformationFromOIDC(OIDCAuthenticationToken token, User currentUserInDb, UserInfo oidcUserInfo) { // get the current authentication details of the user Authentication auth = SecurityContextHolder.getContext().getAuthentication(); enrichAuthoritiesWithStoredAuthorities(currentUserInDb, auth); // check for profile updates since the last login String oidcUpdatedTime = token.getUserInfo().getUpdatedTime(); // oidc time: "20150701_090039" // oidc format: "yyyyMMdd_HHmmss" SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); User savedUser = null; try { Date date = sdf.parse(oidcUpdatedTime); if (currentUserInDb.getEmail() == null || currentUserInDb.getLastupdatedAt().getTime() > date.getTime()) { currentUserInDb.setFullName(oidcUserInfo.getName()); currentUserInDb.setEmail(oidcUserInfo.getEmail()); savedUser = userService.save(currentUserInDb); } else { savedUser = currentUserInDb; } } catch (ParseException e) { e.printStackTrace(); } return savedUser; } private User createNewUserFirstLogin(OIDCAuthenticationToken token, String subId, String issuer, UserInfo oidcUserInfo) { // create a new user User user = new User(); // check for colliding user names (via preferred user name) String prefferedUsername = oidcUserInfo.getPreferredUsername(); User userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername); int i = 0; if (userWithGivenPreferredUserName != null) { while (userWithGivenPreferredUserName != null) { prefferedUsername = oidcUserInfo.getPreferredUsername() + "#" + i; userWithGivenPreferredUserName = userService.findByUsername(prefferedUsername); } } user.setUsername(prefferedUsername); user.setFullName(oidcUserInfo.getName()); user.setEmail(oidcUserInfo.getEmail()); user.setEnabled(true); // apply roles List<Role> roleList = new ArrayList<Role>(); Role userRole = roleService.findByName("ROLE_USER"); if (userRole == null) { // create initial roles String newUserRoleName = "ROLE_USER"; userRole = createNewUserRole(newUserRoleName); String newAdminRoleName = "ROLE_ADMIN"; Role adminRole = createNewUserRole(newAdminRoleName); // For the first user add the admin role roleList.add(adminRole); } else { roleList.add(userRole); } user.setRoleList(roleList); // A password is required so we set a uuid generated one if ("development".equals(env.getProperty("lds.app.instance"))) { user.setPassword("pass"); } else { user.setPassword(UUID.randomUUID().toString()); } user.setSubId(subId); user.setIssuer(issuer); String oidcUpdatedTime = token.getUserInfo().getUpdatedTime(); // oidc time: "20150701_090039" // oidc format: "yyyyMMdd_HHmmss" SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); try { Date date = sdf.parse(oidcUpdatedTime); user.setLastupdatedAt(date); } catch (ParseException e) { e.printStackTrace(); } User savedUser = userService.save(user); // update security context Authentication auth = SecurityContextHolder.getContext().getAuthentication(); enrichAuthoritiesWithStoredAuthorities(user, auth); return savedUser; } @Override public void publishEvent(Object event) { throw new RuntimeException("Publish event call failed not implemented yet."); } private void enrichAuthoritiesWithStoredAuthorities(User currentUserInDb, Authentication auth) { Collection<? extends GrantedAuthority> authorities = auth.getAuthorities(); final SubjectIssuerGrantedAuthority[] oidcAuthority = new SubjectIssuerGrantedAuthority[1]; authorities.forEach(authority -> { if (authority instanceof SubjectIssuerGrantedAuthority) { // extract the oidc authority information oidcAuthority[0] = (SubjectIssuerGrantedAuthority) authority; } }); // create new authorities that includes the authorities stored in the database // as well as the oidc authority ArrayList<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>(); newAuthorities.add(oidcAuthority[0]); currentUserInDb.getRoleList().forEach(role -> { newAuthorities.add(new SimpleGrantedAuthority(role.getName())); }); try { Field authoritiesField = AbstractAuthenticationToken.class.getDeclaredField("authorities"); authoritiesField.setAccessible(true); authoritiesField.set(auth, newAuthorities); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); } // update the authority information in the security context SecurityContextHolder.getContext().setAuthentication(auth); } private Role createNewUserRole(String newRoleName) { Role newUserRole = new Role(); newUserRole.setName(newRoleName); return roleService.save(newUserRole); } }); http.addFilterBefore(oidcFilter, AbstractPreAuthenticatedProcessingFilter.class).csrf() .requireCsrfProtectionMatcher(new RequestMatcher() { private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$"); private RegexRequestMatcher apiMatcher = new RegexRequestMatcher("/v[0-9]*/.*", null); @Override public boolean matches(HttpServletRequest request) { // CSRF disabled on allowedMethod if (allowedMethods.matcher(request.getMethod()).matches()) return false; // CSRF disabled on api calls if (apiMatcher.matches(request)) return false; // CSRF enables for other requests //TODO change later on return false; } }).and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and().logout() .logoutSuccessHandler(logoutSuccessHandler()).deleteCookies("JSESSIONID") .deleteCookies("sessionID"); }
From source file:org.ambraproject.wombat.config.SpringSecurityConfiguration.java
@Override protected void configure(HttpSecurity http) throws Exception { if (runtimeConfiguration.getCasConfiguration().isPresent()) { http.addFilter(casAuthenticationFilter()).addFilterBefore(requestLogoutFilter(), LogoutFilter.class) .addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class).authorizeRequests() .antMatchers(USER_AUTH_INTERCEPT_PATTERN).fullyAuthenticated().and().authorizeRequests() .requestMatchers(new RequestMatcher() { public boolean matches(HttpServletRequest request) { String path = "" + request.getServletPath() + request.getPathInfo(); String host = "" + request.getServerName().toLowerCase(); return (path != null && (path.contains("DesktopApertaRxiv") || host.contains("apertarxiv"))); }// ww w.ja v a 2 s . c o m }).permitAll().and().authorizeRequests().antMatchers(NEW_COMMENT_AUTH_INTERCEPT_PATTERN) .fullyAuthenticated().and().authorizeRequests().antMatchers(FLAG_COMMENT_AUTH_INTERCEPT_PATTERN) .fullyAuthenticated(); http.exceptionHandling().authenticationEntryPoint(casAuthenticationEntryPoint()); http.csrf().disable(); } }