1

Tengo un estancamiento en Spring Security, sobre todo al activar HTTPS, no me deja loguearme por el módulo por defecto. Todo el código fuente lo tengo en la pregunta en inglés: https://stackoverflow.com/questions/63298729/https-403-access-denied-login-default-module-spring-security

Spring Console

2020-08-10 10:43:43.171  INFO 2956 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9898 (https) 8082 (http) with context path ''
2020-08-10 10:43:43.173  INFO 2956 --- [  restartedMain] c.p.conexiona.ConexionaApplication       : Started ConexionaApplication in 9.651 seconds (JVM running for 12.344)
2020-08-10 10:43:43.175 DEBUG 2956 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Creating new Restarter for thread Thread[main,5,main]
2020-08-10 10:43:43.175 DEBUG 2956 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Immediately restarting application
2020-08-10 10:43:43.175 DEBUG 2956 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Created RestartClassLoader org.springframework.boot.devtools.restart.classloader.RestartClassLoader@6fd62c96
2020-08-10 10:43:43.175 DEBUG 2956 --- [  restartedMain] o.s.boot.devtools.restart.Restarter      : Starting application com.practicas.conexiona.ConexionaApplication with URLs [file:/C:/Users/canro/IdeaProjects/conexiona_cuatro/target/classes/]
2020-08-10 10:54:41.273  INFO 2956 --- [io-9898-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-10 10:54:41.273  INFO 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-10 10:54:41.273 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet        : Detected StandardServletMultipartResolver
2020-08-10 10:54:41.281 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet        : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2020-08-10 10:54:41.281  INFO 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet        : Completed initialization in 8 ms
2020-08-10 10:54:41.317 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error", parameters={}
2020-08-10 10:54:41.325 DEBUG 2956 --- [io-9898-exec-10] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-08-10 10:54:41.353 DEBUG 2956 --- [io-9898-exec-10] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-08-10 10:54:41.361 DEBUG 2956 --- [io-9898-exec-10] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 403
2020-08-10 10:54:41.697 DEBUG 2956 --- [nio-9898-exec-2] o.s.web.servlet.DispatcherServlet        : "ERROR" dispatch for GET "/error", parameters={}
2020-08-10 10:54:41.909 DEBUG 2956 --- [nio-9898-exec-2] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml(HttpServletRequest, HttpServletResponse)
2020-08-10 10:54:41.917 DEBUG 2956 --- [nio-9898-exec-2] o.s.w.s.v.ContentNegotiatingViewResolver : Selected 'text/html' given [text/html, text/html;q=0.8]
2020-08-10 10:54:41.921 DEBUG 2956 --- [nio-9898-exec-2] o.s.web.servlet.DispatcherServlet        : Exiting from "ERROR" dispatch, status 403

Application.class

@Configuration
public class Application {

    public static void main(String... args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.setAdditionalProfiles("ssl");
        application.run(args);
    }

    @Bean
    public ServletWebServerFactory servletContainer() {
        // Enable SSL Trafic
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };

        // Add HTTP to HTTPS redirect
        tomcat.addAdditionalTomcatConnectors(httpToHttpsRedirectConnector());

        return tomcat;
    }

    /*
    We need to redirect from HTTP to HTTPS. Without SSL, this application used
    port 8082. With SSL it will use port 8443. So, any request for 8082 needs to be
    redirected to HTTPS on 9898.
     */
    private Connector httpToHttpsRedirectConnector() {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(8082);
        connector.setSecure(false);
        connector.setRedirectPort(9898);
        return connector;
    }

application.properties

server.port=9898
# The format used for the keystore. It could be set to JKS in case it is a JKS file
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store= src/main/resources/crmiguez.p12
# The password used to generate the certificate
server.ssl.key-store-password=password
# The alias mapped to the certificate
server.ssl.key-alias=crmiguez

server.ssl.enabled=true

#trust store location
trust.store= src/main/resources/crmiguez.p12
#trust store password
trust.store.password=password

SecurityConfiguration.class

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private UserPrincipalDetailsService userPrincipalDetailsService;
    private UserRepository userRepository;

    public SecurityConfiguration(UserPrincipalDetailsService userPrincipalDetailsService, UserRepository userRepository) {
        this.userPrincipalDetailsService = userPrincipalDetailsService;
        this.userRepository = userRepository;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                // remove csrf and state in session because in jwt we do not need them
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // add jwt filters (1. authentication, 2. authorization)
                .addFilter(new JwtAuthenticationFilter(authenticationManager()))
                .addFilter(new JwtAuthorizationFilter(authenticationManager(),  this.userRepository))
                .authorizeRequests()
                // configure access rules
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers( "/api/v1/usermanage/**").hasRole("GUEST")
                .antMatchers( "/api/v1/accountmanage/**").hasRole("ADMIN")
                .antMatchers("/api/v1/usermanage/**").hasRole("ADMIN")
                .anyRequest().authenticated();
    }

    @Bean
    DaoAuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(this.userPrincipalDetailsService);

        return daoAuthenticationProvider;
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

La configuración JWT es la misma que Romanian Coder código fuente

User.java (en esta clase he hecho dos getters para el tema de permisos y roles, en sendas listas)

@Entity(name = "User")
@Table
public class User implements Serializable {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @Size(max = 36)
    @Column(name = "userId")
    private String userId;

    @JoinColumn(name = "accountId", referencedColumnName = "accountId", nullable = false)
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Account account;

    @Column(name = "userName")
    private String userName;

    @Column(name = "emailAddress")
    private String emailAddress;

    @Column(name = "password")
    private String password;

    @Column(name = "enabled")
    @ColumnDefault(value = "1")
    private Integer enabled;

    @Column(name = "lastLogin")
    private Long lastLogin;

    @OneToMany(
            mappedBy = "user",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private Set<UserGroupUser> userGroups = new HashSet<>();

    public User() {
    }

    public User (String userId, String accountId, String userName, String emailAddress, String password, Integer enabled, Long lastLogin) {
        this.userId = userId;
        this.account = new Account(accountId);
        this.userName = userName;
        this.emailAddress = emailAddress;
        this.password = password;
        this.enabled = enabled;
        this.lastLogin = lastLogin;
    }

    public User(String userId, Account account, String userName, String emailAddress, String password, Integer enabled, Long lastLogin) {
        this.userId = userId;
        this.account = account;
        this.userName = userName;
        this.emailAddress = emailAddress;
        this.password = password;
        this.enabled = enabled;
        this.lastLogin = lastLogin;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public Account getAccount() { return account; }

    public void setAccount(Account account) { this.account = account; }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getEnabled() {
        return enabled;
    }

    public void setEnabled(Integer enabled) {
        this.enabled = enabled;
    }

    public Long getLastLogin() {
        return lastLogin;
    }

    public void setLastLogin(Long lastLogin) {
        this.lastLogin = lastLogin;
    }

    public Set<UserGroupUser> getUserGroups() {
        return userGroups;
    }

    public void setUserGroups(Set<UserGroupUser> userGroupUser) {
        this.userGroups = userGroupUser;
    }

    public List<String> getRoleList(){
        List<String> userRoleList = new ArrayList<>();
        if(this.userGroups.size() > 0){
            for (UserGroupUser usu: userGroups) {
                if (usu.getUserAdmin() == 1)
                    userRoleList.add("ADMIN");
                else
                    userRoleList.add("GUEST");
            }
            return userRoleList;
        }
        return new ArrayList<>();
    }

    public List<String> getPermissionList(){
        List<String> userPermissionsList = new ArrayList<>();
        if(this.userGroups.size() > 0){
            for (UserGroupUser usu: userGroups) {
                if (usu.getUserAdmin() == 1){
                    userPermissionsList.add("ACCOUNT_WRITE");
                    userPermissionsList.add("ACCOUNT_READ");
                    userPermissionsList.add("USER_WRITE");
                    userPermissionsList.add("USER_READ");
                }
                else{
                    userPermissionsList.add("USER_READ");
                }
            }
            return userPermissionsList;
        }
        return new ArrayList<>();
    }
}

Comandos consola SO para archivo p12

keytool -genkeypair -alias crmiguez -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore crmiguez.p12 -validity 3650

keytool -genkeypair -alias crmiguez -keyalg RSA -keysize 2048 -keystore crmiguez.jks -validity 3650

keytool -importkeystore -srckeystore crmiguez.jks -destkeystore crmiguez.jks -deststoretype pkcs12

Similar questions in Stackoverflow: https://stackoverflow.com/questions/58710908/jwt-token-in-spring-boot-configuration-problem

https://stackoverflow.com/questions/26739167/jwt-json-web-token-automatic-prolongation-of-expiration?rq=1

https://stackoverflow.com/questions/22587992/jwt-and-web-api-jwtauthforwebapi-looking-for-an-example?noredirect=1&lq=1

https://stackoverflow.com/questions/31746466/spring-security-always-returns-http-403/41247428

If I put https://localhost:9898/login on the browser, it appears like this:

403 Denied on login Spring Security

In case of Insomnia, the error was the following:

Proving login module in Insomnia App

Muchas gracias. :)

Actualizado 11-8-20: He añadido GET, pero ha cambiado a 404

introducir la descripción de la imagen aquí

4
  • 1
    Por favor, copia el código aquí. Si la pregunta acaba cerrada y borrada en SO en inglés, desde aquí no se podrá visitar por usuarios que tengan menos de 10.000 puntos de reputación (mínima puntuación para ver preguntas borradas. el 10 ago. 2020 a las 9:19
  • 1
    Por otro lado, creo que el problema es que has permitido hacer una petición POST a la url .../login, pero no una petición GET, que es lo que tu navegador intenta cuando pones una URL en la barra de direcciones el 10 ago. 2020 a las 9:20
  • 1
    La pregunta en el sitio en Inglés ha sido cerrada por lo que muchos, aunque quisieran ayudarte, no podrán ver los detalles. Sugiero que coloques todos los detalles de tu pregunta. No me parece mal si publicas en ambos sitios, si con eso quieres aumentar las posibilidades de encontrar una respuesta, pero debes mantener cada pregunta por separado (obviamente debes intentar que ambas preguntas sean claras, concretas e idealmente tengan un ejemplo mínimo verificable. Un saludo.
    – jachguate
    el 10 ago. 2020 a las 9:52
  • Voy a actualizar la pregunta. Muchas gracias.
    – user39427
    el 11 ago. 2020 a las 9:33

1 respuesta 1

0

Creo que estás teniendo mala suerte con tus pruebas:

  • Cuando pones http://localhost:9898/login en un navegador, éste hace una petición GET, pero tu configuración en Spring especifica que la única petición aceptada a esa URL es POST.

  • Cuando has tratado de usar Insomnia, indicando correctamente que usara el método POST, has usado la URL https://localhost:9898/login. Es decir, has intentado usar una conexión segura que pide un certificado SSL válido para el dominio localhost, que obviamente no tienes. Y por tanto te ha dado un fallo de certificado no válido.

Solución: intenta con Insomnia o Postal hacer una petición POST a http://localhost:9898/login, sin la s

6
  • Buena observación, pero por si no te habías fijado he puesto en application.properties server.ssl.key-store= src/main/resources/crmiguez.p12, y en Insomnia no lo detecta. Si quito la s del HTTP, me indica que falta TLS.
    – user39427
    el 11 ago. 2020 a las 11:28
  • Lo que necesito saber si existe posibilidad de loguearse, tanto en el navegador, como en las aplicaciones estilo Insomnia, por favor.
    – user39427
    el 11 ago. 2020 a las 11:31
  • Me han dicho que es posible activar HTTPS sin el certificado SSL y emplear sin problemas el JWT. Cómo se resolvería en la configuración de seguridad?
    – user39427
    el 11 ago. 2020 a las 12:38
  • Vale, lo acabo de comprobar por mí misma. @PabloLozano muchas gracias. Puedo tener algunos días que no me salgan pruebas, pero estoy en el derecho de equivocarme para aprender xD
    – user39427
    el 12 ago. 2020 a las 7:39
  • 1
    Equivocarte es casi la única forma de aprender en la programación. A veces se aprende de las equivocaciones de otros, pero no es tan común ;) el 12 ago. 2020 a las 7:40

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.