Example usage for org.springframework.security.config.annotation.web.builders HttpSecurity addFilterBefore

List of usage examples for org.springframework.security.config.annotation.web.builders HttpSecurity addFilterBefore

Introduction

In this page you can find the example usage for org.springframework.security.config.annotation.web.builders HttpSecurity addFilterBefore.

Prototype

public HttpSecurity addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) 

Source Link

Usage

From source file:shiver.me.timbers.security.spring.StatelessWebSecurityConfigurerAdapter.java

@Override
protected final void configure(HttpSecurity http) throws Exception {

    final TokenParser<T> tokenParser = tokenParser(secret);
    final XAuthTokenHttpServletBinder<T> xAuthTokenHttpServletBinder = xAuthTokenHttpServletBinder(tokenParser);
    final AuthenticationHttpServletBinder<T> authenticationHttpServletBinder = authenticationHttpServletBinder(
            xAuthTokenHttpServletBinder, authenticationConverter());
    final ExceptionMapper<ServletException> exceptionMapper = servletExceptionExceptionMapper();

    if (!customTokenParser) {
        configure((JwtTokenParser) tokenParser);
    }// w  ww .  ja  va 2s  .co  m
    if (!customXAuthTokenHttpServletBinder) {
        configure(xAuthTokenHttpServletBinder);
    }

    final StatelessAuthenticationSuccessHandler statelessAuthenticationSuccessHandler = statelessAuthenticationSuccessHandler(
            authenticationHttpServletBinder, simpleUrlAuthenticationSuccessHandler(defaultSuccessUrl()),
            exceptionMapper);
    final StatelessAuthenticationFilter statelessAuthenticationFilter = statelessAuthenticationFilter(
            authenticationHttpServletBinder, exceptionMapper);

    // Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
    // previously existing session.
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    // The CSRF prevention is disabled because it requires the session, which of course is not available in a
    // stateless application. It also greatly complicates the requirements for the sign in POST request.
    http.csrf().disable();
    // Override the sign in success handler with the stateless implementation.
    http.formLogin().successHandler(statelessAuthenticationSuccessHandler);
    // Add our stateless authentication filter before the default sign in filter. The default sign in filter is
    // still used for the initial sign in, but once a user is authenticated we need to by pass it.
    http.addFilterBefore(statelessAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

    configureFurther(http);
}

From source file:scratch.cucumber.example.SecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {

    // The http.formLogin().defaultSuccessUrl("/path/") method is required when using stateless Spring Security
    // because the session cannot be used to redirect to the page that was requested while signed out. Unfortunately
    // using this configuration method will cause our custom success handler (below) to be overridden with the
    // default success handler. So to replicate the defaultSuccessUrl("/path/") configuration we will instead
    // correctly configure and delegate to the default success handler.
    final SimpleUrlAuthenticationSuccessHandler delegate = new SimpleUrlAuthenticationSuccessHandler();
    delegate.setDefaultTargetUrl("/spring/");

    // Make Spring Security stateless. This means no session will be created by Spring Security, nor will it use any
    // previously existing session.
    http.sessionManagement().sessionCreationPolicy(STATELESS);
    // Disable the CSRF prevention because it requires the session, which of course is not available in a
    // stateless application. It also greatly complicates the requirements for the sign in POST request.
    http.csrf().disable();//from  w  w  w .  j a  va  2s.  com
    // Viewing any page requires authentication.
    http.authorizeRequests().anyRequest().authenticated();
    http.formLogin()
            // Viewing the sign in page does not require authentication.
            .loginPage("/spring/signIn").permitAll()
            // Override the sign in success handler with our stateless implementation. This will update the response
            // with any headers and cookies that are required for subsequent authenticated requests.
            .successHandler(new StatelessAuthenticationSuccessHandler(authenticationBinder, delegate));
    http.logout().logoutUrl("/spring/signOut").logoutSuccessUrl("/spring/");
    // Add our stateless authentication filter before the default sign in filter. The default sign in filter is
    // still used for the initial sign in, but if a user is authenticated we need to acknowledge this before it is
    // reached.
    http.addFilterBefore(new StatelessAuthenticationFilter(authenticationBinder, securityContextHolder),
            UsernamePasswordAuthenticationFilter.class);
}

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//w ww  . jav  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:olympus.portal.security.WebSecurityConfig.java

@Override
protected void configure(HttpSecurity http) throws Exception {
    /*http/*from   w w  w.ja v  a2  s.co  m*/
    .httpBasic()
        .authenticationEntryPoint(samlEntryPoint());*/

    http.csrf().disable()
            /*.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()*/
            .authorizeRequests().antMatchers("/", "/error", "/saml/**").permitAll().antMatchers("/login")
            .anonymous().anyRequest().authenticated().and().logout().permitAll().logoutSuccessUrl("/");

    http.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
}

From source file:org.opentestsystem.ap.iat.config.SecurityConfig.java

/**
 * Defines the web based security configuration.
 *
 * @param http It allows configuring web based security for specific http requests.
 * @throws Exception/*from   w ww  .  j a  v  a  2 s. c o  m*/
 */
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().authenticationEntryPoint(samlEntryPoint());
    http.csrf().disable();
    http.addFilterBefore(forwardedHeaderFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(metadataGeneratorFilter(), ForwardedHeaderFilter.class)
            .addFilterAfter(samlFilter(), BasicAuthenticationFilter.class);
    http.headers().frameOptions().sameOrigin();
    http.authorizeRequests()
            .antMatchers("/saml/**", "/manage/**/health**", "/manage/**/info**", "/assets/**", "**.js",
                    "favicon.**", "/fontawesome**", "/glyphicons**", "/api/sec/**", "/api/ivs/**",
                    "/error/403.html", "/keepalive")
            .permitAll();
    http.authorizeRequests().antMatchers("/**").hasAnyRole("ADMIN", "USER");
    http.logout().logoutSuccessUrl("/");

    http.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
}

From source file:org.springframework.cloud.dataflow.server.config.security.OAuthSecurityConfiguration.java

@Override
protected void configure(HttpSecurity http) throws Exception {

    final RequestMatcher textHtmlMatcher = new MediaTypeRequestMatcher(
            new BrowserDetectingContentNegotiationStrategy(), MediaType.TEXT_HTML);

    final BasicAuthenticationEntryPoint basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
    basicAuthenticationEntryPoint.setRealmName(securityProperties.getBasic().getRealm());
    basicAuthenticationEntryPoint.afterPropertiesSet();

    final Filter oauthFilter = oauthFilter();
    BasicAuthenticationFilter basicAuthenticationFilter = new BasicAuthenticationFilter(providerManager(),
            basicAuthenticationEntryPoint);

    http.addFilterAfter(oauthFilter, basicAuthenticationFilter.getClass());
    http.addFilterBefore(basicAuthenticationFilter, oauthFilter.getClass());
    http.addFilterBefore(oAuth2AuthenticationProcessingFilter(), basicAuthenticationFilter.getClass());

    http.authorizeRequests()/* w  ww  .  j  a v a2s . c om*/
            .antMatchers("/security/info**", "/login**", dashboard("/logout-success-oauth.html"),
                    dashboard("/styles/**"), dashboard("/images/**"), dashboard("/fonts/**"),
                    dashboard("/lib/**"))
            .permitAll().anyRequest().authenticated().and().httpBasic().and().logout()
            .logoutSuccessUrl(dashboard("/logout-success-oauth.html")).and().csrf().disable()
            .exceptionHandling()
            .defaultAuthenticationEntryPointFor(new LoginUrlAuthenticationEntryPoint("/login"), textHtmlMatcher)
            .defaultAuthenticationEntryPointFor(basicAuthenticationEntryPoint, AnyRequestMatcher.INSTANCE);

    securityStateBean.setAuthenticationEnabled(true);
    securityStateBean.setAuthorizationEnabled(false);
}