#Spring Security

98 messages · Page 1 of 1 (latest)

keen drift
#

I dont know why but i am not getting default login page after enabling the @WebSecurity annoation ..


import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

}

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityIntializer extends AbstractSecurityWebApplicationInitializer {

}
``` This is the classes and in the photo that is my project structure . Can anyone Help
ivory fiberBOT
#

This post has been reserved for your question.

Hey @keen drift! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

carmine sundial
#

What actually happens?

keen drift
#

basically i have started spring security module and trying to start the basic security to my endpoint of the controllers via 2 classes called SecurityConfigurationand SecurityIntializer but when i start the project then i didnot get any default login page for security purpose . I think the security page is automatically added to the project using the @Enable Web Security annoatation right ?

dark ether
#

hi. I will show my code.

#
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    AuthDetailsServiceImpl userDetailsService;

    @Autowired
    private AuthEntryPointJwt  unauthorizedHandler;
    @Bean
    public AuthTokenFilter authenticationJwtTokenFilter() {
        return new AuthTokenFilter();
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();

        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable())
                .cors(cors -> cors.disable())
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth ->
                        auth.requestMatchers("/auth/**").permitAll()
                                .requestMatchers("/test/**").permitAll()
                                .requestMatchers("/error").permitAll()
                                .anyRequest().authenticated()
                );

        http.authenticationProvider(authenticationProvider());

        http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
#

please try it.

keen drift
# dark ether hi. I will show my code.

Right now I am following a tutorial and that guy just got a login page for authentication and authorisation after just adding the two classes for config and initialisation as I mentioned above . So is that thing removed now bcz that video is 3 yrs old !

carmine sundial
#

Can you show your pom.xml? I think the default login page is there only if you use Spring Boot

keen drift
#

i am not using spring boot now either i am using spring mvc instead

#

What should be the right ?

dark ether
#

what version of maven is your project?

keen drift
#

I have already given the pom.xml

#

@carmine sundial

carmine sundial
carmine sundial
carmine sundial
#

Which are available?

#

Btw Spring 5 will be out of Open Source support soon

keen drift
#

Hmm so I have to use spring 6 for my upcoming projects ?

carmine sundial
#

I would strongly recommend doing that

keen drift
#

import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@EnableWebSecurity(debug = true)
public class Config extends WebSecurityConfigurerAdapter {

     @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .antMatchers("/public/**").permitAll()  // Permit access to public resources
                    .anyRequest().authenticated()  // All other requests must be authenticated
                    .and()
                .formLogin()
                    .loginPage("/login")  // Custom login page URL
                    .defaultSuccessUrl("/dashboard")  // Redirect to this URL after successful login
                    .permitAll()  // Allow everyone to access the login page
                    .and()
                .logout()
                    .logoutUrl("/logout")  // URL to trigger logout
                    .logoutSuccessUrl("/login?logout")  // Redirect to this URL after logout
                    .permitAll();  // Allow everyone to access the logout URL

            // Disable Cross-Site Request Forgery (CSRF) protection for simplicity
            http.csrf().disable();
        }

        // Bean for PasswordEncoder (BCryptPasswordEncoder)
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
}
``` i did it but not get anything its same
dark ether
#

SecurityConfig.java

import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()  // Require authentication for all requests
                .and()
            .formLogin()  // Enable form-based authentication
                .loginPage("/login")  // Specify the custom login page URL
                .permitAll()  // Allow everyone to see the login page
                .and()
            .logout()  // Enable logout functionality
                .permitAll();
    }

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

If you do not create a custom login page and do not specify loginPage("/login"), Spring Security will provide its default login page at the /login endpoint. However, the configuration above ensures that your application uses form-based authentication and handles the login functionality appropriately.

#

If you follow these steps and still do not see the default login page, make sure there are no other configurations or security settings that might be overriding these settings. Double-check your application logs for any errors or warnings related to security configuration.

keen drift
#


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;




@Controller
public class login {
    
    @ResponseBody
    @GetMapping("/hii")
    public String name() {
        return"Hii";
    }
 
}
``` This is my controller for checking is this Ok ?
#

@dark ether

dark ether
#

this is accurate controller.

#
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class LoginController {

    @GetMapping("/login")
    public String login() {
        return "login";
    }
}
keen drift
#

Alright waiting for the response

dark ether
#

do you know @ResponseBody annotation?

#

Ensures that the response from the name() method is written directly to the HTTP response body.
I think your controller is right.

carmine sundial
#

If you don't have @ResponseBody, it typically tries to render the response

keen drift
#

I have already added the responseBody annotation

keen drift
carmine sundial
#

@ResponseBody won't show any login page

keen drift
#


import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;




@Controller
public class login {
    
    
    @GetMapping("/hii")
    public String name() {
        return"Hi";
    }
 
}
``` ok now i have removed it and also added a hi.jsp to the retrun but still i can access the jps page or u can say /hii endpoint
carmine sundial
#

Is your security configuration attempting to prevent that in any way?

keen drift
#

Wdym ?

carmine sundial
#

Why should it not be accessible?

keen drift
#

import org.springframework.context.annotation.Bean;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


@EnableWebSecurity(debug = true)
public class Config extends WebSecurityConfigurerAdapter {

     @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()  // Require authentication for all requests
                    .and()
                .formLogin()  // Enable form-based authentication
                    .loginPage("/login")  // Specify the custom login page URL
                    .permitAll()  // Allow everyone to see the login page
                    .and()
                .logout()  // Enable logout functionality
                    .permitAll();
        }

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

This is what I did

carmine sundial
#

You called your package config?

#

Can you show your beans.xml?

keen drift
keen drift
carmine sundial
#

Do you have such a file?

#

Spring doesn't scan all packages, it only scans package under some root package

keen drift
#

No

#

I have web.xml

carmine sundial
#

So Spring doesn't know anything about your Config class

keen drift
#

I think no !

#
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd
    
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    ">
    
      <context:component-scan base-package="com.controllers"></context:component-scan>
      
      <bean id = "viewresolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
      
      <property name="prefix" value="/WEB-INF/lib/view/"></property>
      <property name="suffix" value=".jsp"></property>
      
      </bean>

</beans>```
carmine sundial
#

that was a typo

#

I wanted to write So instead of Do

#

this wasn't a question

carmine sundial
#

That means Spring will only find stuff in com.controllers

keen drift
#
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd
    
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    ">
    
      <context:component-scan base-package="com.controllers , config"></context:component-scan>
      
      <bean id = "viewresolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
      
      <property name="prefix" value="/WEB-INF/lib/view/"></property>
      <property name="suffix" value=".jsp"></property>
      
      </bean>

</beans>``` is this ok
carmine sundial
#

Why don't you just create one common package and put all your application classes in subpackages?

carmine sundial
#

no

#

if your base package is com.yourapplication and you have classes in °com.yourapplication.controllersandcom.yourapplication.config`, these should be detected

keen drift
#

Package are not scanning

carmine sundial
#

you need to set it to com.application

#

not com.application.*

keen drift
#

Still 404 error

#
00:23:10.464 [http-nio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - No mapping for GET /LoginPage/
00:23:10.467 [http-nio-8080-exec-1] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 404 NOT_FOUND```
carmine sundial
#

Do you have a handler for that?

keen drift
#

Yess /hii

carmine sundial
#

And you are accessing /hii in your browser?

keen drift
#

Yess

#

like this

carmine sundial
#

How are you running the application?

#

Do you have a servers view in Eclipse?

keen drift
#

like this ?

#

when i write this in scan com.applicationcom.controllers then it works but not with com.applicationcom

carmine sundial
#

com.application

#

not com.applicationcom

#

but ig if it works, it's fine

keen drift
#

i did the same project on spring boot and it runs perfectly @carmine sundial

#

some one said to me that WebsecurityConfigurerAdapter is deprecated…
is deprecated is that real ?

keen drift
ivory fiberBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.

copper bridge
#

What did I said wrong?

carmine sundial
#

?

copper bridge
#

He blocked me or removed from friends. I want to get him back. tried to search from history.

carmine sundial
copper bridge
#

ok. Lock this question.

ivory fiberBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.