5
respostas

Spring security

Não estou conseguindo trabalhar com CSRF Attacks, mesmo tirando esta parte do código http.csrf().disable();.

Sobre o item estou colocando nas páginas html, mas dá erro

<meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
5 respostas

Olá Guilherme, tudo bem?

Qual é o erro apresentado quando você informa os meta tags? Você está usando JSP ou Spring MVC?

Na submissão do formulário você colocou o token?

Exemplo:

<form action="${logoutUrl}"
    method="post">
<input type="submit"
    value="Log out" />
<input type="hidden"
    name="${_csrf.parameterName}"
    value="${_csrf.token}"/>
</form>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
    xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<title>Nota Fiscal Eletrônica de Serviços</title>
<link rel="shortcut icon" th:href="@{/resources/img/iconeDesif.ico}"
    type="image/x-icon" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link th:include="jsCss/css" th:remove="tag"></link>
<link th:include="jsCss/js" th:remove="tag"></link>

<link rel="stylesheet" type="text/css"
    th:href="@{/resources/css/keyboard/keyboard.css}">
<script type="text/javascript"
    th:src="@{/resources/js/keyboard/keyboard.js}" charset="UTF-8"></script>
<script type="text/javascript"
    th:src="@{/resources/js/keyboard/include/keyboard.js}" charset="UTF-8"></script>

</head>
<body class="gray-bg">
    <div class="loginColumns animated fadeInDown ibox-content">
        <div class="row">
            <div style="text-align: center;">
                <h1 class="logo-name">NFSe +</h1>
            </div>
            <br />
            <div class="col-md-6">
                <h2 class="font-bold">Bem vindo ao sistema de nota Foscal
                    Eletrônica de Serviços</h2>
            </div>
            <div class="col-md-6">
                <div th:if="${param.error}">
                    <script th:inline="javascript">
                                    /*<![CDATA[*/
                                    var mensagemErro = [[${session.SPRING_SECURITY_LAST_EXCEPTION.message}]];
                                    /*]]>*/
                                    toastr.error(mensagemErro, "Error ...");
                                </script>
                </div>
                <div th:if="${param.logout}">
                    <script th:inline="javascript">
                            toastr.info("Obrigado por utilizar nosso sistema !", "Sucesso ...");
                        </script>
                </div>
                <div class="ibox-content">
                    <form th:action="@{/login}" method="post">
                        <input type="hidden" name="${_csrf.parameterName}"
                            value="${_csrf.token}" />
                        <div class="form-group">
                            <input name="username" class="form-control documento"
                                placeholder="Informe o usuário !" maxlength="18"
                                data-toggle="tooltip" data-placement="bottom"
                                title="Informe o usuário !"
                                data-original-title="Informe o usuário !" />
                        </div>
                        <div class="form-group">
                            <input type="password" name="password"
                                class="form-control keyboardInput" placeholder="Informe a senha"
                                maxlength="255" data-toggle="tooltip" data-placement="bottom"
                                title="Informe a senha !"
                                data-original-title="Informe a senha !" />
                        </div>

                        <button type="submit" class="btn btn-primary block full-width m-b">Entrar</button>
                        <a th:href="@{/esqueceuSenha}"> <small>Esqueceu a
                                senha (Clique aqui) ?</small>
                        </a>
                        <div class="form-group">
                            <input type="checkbox" id="remember-me" name="remember-me" /> <label
                                for="remember-me">Lembrar?</label>
                        </div>
                    </form>
                    <form th:action="@{/loginCertificadoDigital}" method="post">
                        <button type="submit" class="btn btn-primary block full-width m-b">Entrar
                            com certificado digital</button>
                    </form>
                </div>
            </div>
        </div>
        <script>
        $(document).ready(
                function() {
                    jQuery("input.documento")
                    .mask("999.999.999-9?9999")
                    .focusout(
                            function(event) {
                                var target, documento, element;
                                target = (event.currentTarget) ? event.currentTarget
                                        : event.srcElement;
                                documento = target.value.replace(
                                        /\D/g, '');
                                element = $(target);
                                element.unmask();
                                if (documento.length < 12) {
                                    element
                                            .mask("999.999.999-9?9999");
                                } else {
                                    element
                                            .mask("99.999.999/9999-99");
                                }
                            });
                }
        );
        </script>

        <hr />
    </div>
    <div class="footer">
        <div th:include="footer" th:remove="tag"></div>
    </div>
</body>
</html>

Código Java do spring security

package br.com.netsoft.seguranca;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
/**
 * @author Guilherme Costa
 */
public class SecurityWebConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginSucessHandler loginSucessHandler;

    @Autowired
    private NotaFiscalSeguranca comercialUserDetailsService;

    /**
     * Utilizamos o passwordEncoder para encriptografar a senha do usuário
     * 
     * @return PasswordEncoder;
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * Sobrescrevendo o metodo configure da classe WebSecurityConfigurerAdapter
     * do pacote
     * org.springframework.security.config.annotation.web.configuration
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // Configuração para todos usuarios do sistema
                .antMatchers("/error/**", "/resources/**", "/jsCss/**", "/webjars/**", "/recuperarSenha").permitAll()
                // Configuração para todos usuarios com permissão de
                // ROLE_ADMINISTRADOR
                .antMatchers("/codigo/**", "/subCodigo/**", "/tipoCredito/**", "/tipoCancelamento/**", "/usuario/**",
                        "/servico/**", "/notaFiscal/**", "/erroAlerta/**", "/credito/**", "/configuracao/**",
                        "/cnaeSubCodigo/**", "/cnae/**", "/erroAlerta/**", "/atualizacaoMonetariaItem/**",
                        "/atualizacaoMonetaria/**", "/dashboardAdmin/**", "/porcentagemReter/**")
                .access("hasRole('ROLE_ADMINISTRADOR')")
                // Configuração para todos usuarios do sistema
                .and().formLogin().loginPage("/login").successHandler(loginSucessHandler).permitAll().and().rememberMe()
                // Logout
                .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).and().sessionManagement()
                .maximumSessions(1).maxSessionsPreventsLogin(true).expiredUrl("/login")
                .sessionRegistry(sessionRegistry());
    }

    // Work around https://jira.spring.io/browse/SEC-2855
    @Bean
    public SessionRegistry sessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }

    /**
     * Sobrescrevendo o metodo configure da classe WebSecurityConfigurerAdapter
     * do pacote
     * org.springframework.security.config.annotation.web.configuration
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(comercialUserDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

Alguma novidade ?