logo
Tags down

shadow

Can not switch off SecurityConfig in SpringBootApplication


By : AITOUGHRABOU
Date : August 01 2020, 12:00 AM
it helps some times I have a SecurityConfig and I authorize requests with JWT tokens. The issue is that I would like to switch off the security config for testing my websockets, because somehow I always receiving 401... , You should add
code :
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

    @Configuration
    public class ApplicationSecurity extends WebSecurityConfigurerAdapter {

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/**");
        }
    }


Share : facebook icon twitter icon

Spring MVC : adding securityConfig.xml along with dispatcherContext.xml


By : Đình Lê Khang
Date : March 29 2020, 07:55 AM
I hope this helps you . Just use import within the root context definiton (dispatcherContext.xml in yr case) file :
code :
<!-- Load spring security related configuration -->
<import resource="classpath:securityConfig.xml"/>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>dispatcherContext.xml securityConfig.xml</param-value>
</context-param>

j_spring_security_check http 404 using SecurityConfig


By : miklosz
Date : March 29 2020, 07:55 AM
I wish this helpful for you I have been facing 404 error with j_spring_security_check for the last couple of days thinking I could figure it out. I have read several of the stack over flow questions relating to this issue but nothing seems to change the outcome. I am hoping someone might be able to catch what I am doing (wrong) or not doing. , Add this and see if it works
code :
http
     .authorizeRequests()                                                                
    .antMatchers("/resources/**", "/login").permitAll()                  
    .antMatchers("/admin/**").hasRole("ADMIN")
protected void configure(HttpSecurity http) throws Exception {

 http
 .authorizeRequests()                                                                
.antMatchers("/resources/**", "/login").permitAll()                  
.antMatchers("/admin/**").hasRole("USER")                           
.and()

.formLogin()
    .loginPage("/login")
    .defaultSuccessUrl("/")
 //   .successHandler(successHandler) //----- to handle user role
    .failureUrl("/loginfailed")             
    .permitAll()
    .and()

.logout()
    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
    .deleteCookies("JSESSIONID")
    .invalidateHttpSession( true )
    .and();                    
<div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Please sign in</h3>
                    </div>
                    <div class="panel-body">
                    <c:if test="${param.logout != null}">
                        <div class="alert alert-danger">
                            Logout Successful
                        </div>
                    </c:if>
                    <c:if test="${not empty error}">
                        <div class="alert alert-danger">
                            Bad Credentials
                        </div>
                    </c:if>
                    <c:url value="/login" var="loginUrl"/>
                        <form:form action="${loginUrl }" method="post">
                        <fieldset>
                            <div class="form-group">
                                User Name : <input class="form-control"  name='username' type="text">
                            </div>
                            <div class="form-group">
                                Password : <input class="form-control"  name='password'  type="password" value="">
                            </div>
                            <input class="btn btn-lg btn-success btn-block" type="submit" value="Login">
                        </fieldset>
                        </form:form>
                    </div>
                </div>
            </div>
        </div>
    </div>
public void configureGlobal( AuthenticationManagerBuilder auth) throws Exception {  
    auth
    .jdbcAuthentication()
    .dataSource(dataSource)
    .usersByUsernameQuery("select userId, password, enabled from Users where userId = ?")
    .authoritiesByUsernameQuery("select userId , role from Users where userId = ?");

}
@Controller
@RequestMapping(value="/login",method= RequestMethod.GET )
public String login(){
    return "login";
}

@RequestMapping(value="/loginfailed", method= RequestMethod.GET )
public String loginError(Model model){
    model.addAttribute("error", "true");
    return "login";
}

@RequestMapping(value= "/logout", method = RequestMethod.POST)
public String logout(Model model){
    model.addAttribute("logout","true");
    return "login";
}

}

SecurityConfig 2 success url for different Roles


By : aarondiek
Date : March 29 2020, 07:55 AM
will help you The best way to do this is to send the user to a URL and then create a controller that processes the default-target-url. For example, the following will send the user to /default:
code :
http
    .formLogin()
        .defaultSuccessUrl("/default")
@Controller
public class DefaultController {
    @RequestMapping("/default")
    public String defaultAfterLogin(HttpServletRequest request) {
        if (request.isUserInRole("ROLE_ADMIN")) {
            return "redirect:/admin/";
        }
        return "redirect:/user/";
    }
}
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
        throws Exception {
        auth
           .inMemoryAuthentication()
               .withUser("admin")
                   .password("admin")
                   .roles("ADMIN")
                   .and()
               .withUser("user")
                   .password("user")
                   .roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .and()
             .formLogin()
                .defaultSuccessUrl("/default")
                .loginPage("/")
                .failureUrl("/")
                .and()
            .logout()
                .logoutSuccessUrl("/")
                .and()
            // It is generally BAD to disable CSRF protection!
            .csrf().disable();
     }
}

SecurityConfig for two Roles


By : user7346100
Date : March 29 2020, 07:55 AM
Does that help Try: http.authorizeRequests().antMatchers("/index","/","/ajouterFiliere").hasAnyRole("RM", "RF").
That should help.

Is it possible to split the SecurityConfig of spring?


By : Deno
Date : March 29 2020, 07:55 AM
To fix the issue you can do If you need to write Multiple HttpSecurity due to spring security docs the easiest is to create a general configuration with some internal @Configuration classes for configuring HttpSecurity
code :
@EnableWebSecurity
public class MultiHttpSecurityConfig {
    @Bean
    public UserDetailsService userDetailsService() throws Exception {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("user").password("password").roles("USER").build());
        manager.createUser(User.withUsername("admin").password("password").roles("USER","ADMIN").build());
        return manager;
    }

    @Configuration
    @Order(1)                                                        
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")                               
                .authorizeRequests()
                    .anyRequest().hasRole("ADMIN")
                    .and()
                .httpBasic();
        }
    }

    @Configuration                                                  
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .authorizeRequests()
                    .anyRequest().authenticated()
                    .and()
                .formLogin();
        }
    }
}
Related Posts Related Posts :
shadow
Privacy Policy - Terms - Contact Us © voile276.org