Spring Security HTTPS - spring

I have the problem, that Spring Security is redirecting me to much. So the browser can't build up the side. Whats wrong with my code?
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.fullyAuthenticated()
.and()
.authorizeRequests()
.antMatchers("/login").permitAll()
.and()
.formLogin()
.and()
.httpBasic()
.and()
.requiresChannel()
.anyRequest()
.requiresSecure()
.and()
.csrf().disable();
}
I thought, that the user would be able to access to "localhost:8585/login", because of the .antMatchers("/login").permitAll() ?

order matters here
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.antMatchers("/login*").anonymous()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.and()
.logout().logoutSuccessUrl("/login.html")
.and()
.httpBasic()
.and()
.requiresChannel()
.anyRequest()
.requiresSecure()
.and()
.csrf().disable();
}

Related

How to exclude actuator from SecurityWebFilterChain authorization

I have the WebSecurityConfiguration class which uses SecurityWebFilterChain to authorize access. Still, I want to exclude actuator from it so I have another bean for it but the endpoint still is not accessible w/o authorization.
#Configuration
public class WebSecurityConfiguration
{
#Order(Ordered.HIGHEST_PRECEDENCE)
#Bean
public SecurityWebFilterChain springSecurityFilterChainExcludeActuator(ServerHttpSecurity http) {
return http.securityMatcher(new NegatedServerWebExchangeMatcher(
ServerWebExchangeMatchers.pathMatchers("/actuator/health")))
.authorizeExchange()
.anyExchange().authenticated()
.and()
.csrf().disable()
.build();
}
#Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http)
{
http.csrf().disable()
.authorizeExchange()
.pathMatchers("/domains/**", "/address/**").permitAll()
.anyExchange().authenticated()
.and()
.httpBasic()
.and()
.formLogin().disable();
return http.build();
}
}
Any thoughts on what I have missed?
PS
Even the simple code below will require to provide authorization when I expect is not required for the actuator
http.authorizeExchange()
.pathMatchers("/actuator/**").permitAll()
.anyExchange().authenticated()
.and()
.httpBasic()
.and()
.formLogin()
.and()
.csrf()
.disable();
return http.build();
You can allow individual endpoints like this:
#Bean
SecurityFilterChain filterChain(final HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(EndpointRequest.to(HealthEndpoint.class)).permitAll()
.anyRequest().authenticated())
.build();
}

Configure Spring Security for multiple login pages in a Spring Boot application

#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AccessDeniedHandler accessDeniedHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home", "/about").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("password").roles("ADMIN");
}
}
The Security Configuration is working fine as expected. Now I am trying to implement 2 login forms each for Admin and User. I tried separating the configuration using #Order but landed on the issue mentioned here Spring boot and spring security multiple login pages
Any better approach to implement the same?
In order to configure two different http elements, let’s create two static classes annotated with #Configuration that extend the WebSecurityConfigurerAdapter. Try configuring something like this:
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AccessDeniedHandler accessDeniedHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/admin*")
.authorizeRequests()
.anyRequest()
.hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/loginAdmin")
.loginProcessingUrl("/admin_login")
.failureUrl("/loginAdmin?error=loginError")
.defaultSuccessUrl("/adminPage")
.and()
.logout()
.logoutUrl("/admin_logout")
.logoutSuccessUrl("/protectedLinks")
.deleteCookies("JSESSIONID")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf().disable();
}
}
And, for normal users:
#Configuration
#Order(2)
public static class SpringSecurityConfig2 extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/user*")
.authorizeRequests()
.anyRequest()
.hasRole("USER")
.and()
.formLogin()
.loginPage("/loginUser")
.loginProcessingUrl("/user_login")
.failureUrl("/loginUser?error=loginError")
.defaultSuccessUrl("/userPage")
.and()
.logout()
.logoutUrl("/user_logout")
.logoutSuccessUrl("/protectedLinks")
.and()
.exceptionHandling()
.accessDeniedPage("/403")
.and()
.csrf().disable();
}
}
Refer http://www.baeldung.com/spring-security-two-login-pages

spring boot security login redirects to / when contextPath set

I've got this working when no contextPath is set. But when I set server.contextPath in application.properties, happens that when logging in http://localhost:8080/t2debt_site/login the page redirects to http://localhost:8080/login. What can be happening, please help!
private static final String[] UNSECURED_RESOURCE_LIST =
new String[]{"/", "/resources/**", "/static/**", "/css/**", "/webjars/**",
"/img/**", "/js/**"};
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(UNSECURED_RESOURCE_LIST).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/index")
.failureUrl("/login?error")
.usernameParameter("email")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/login")
.permitAll()
.and()
.rememberMe();
}
#Override
public void configure(WebSecurity security) {
//security.ignoring().antMatchers("/css/**","/img/**","/js/**");
//security.ignoring().antMatchers("/static/**");
security.ignoring().antMatchers(UNSECURED_RESOURCE_LIST);
//security.ignoring().antMatchers("/resources/**");
}

Spring security: Redirect unauthorised url

#PreAuthorize("hasPermission(#id,'Integer','write')")
#RequestMapping(value="events/{id}/edit",method=RequestMethod.GET)
public String edit(Model model,#PathVariable("id") int id) {
model.addAttribute("event", eventService.getEvent(id));
return "events/edit";
}
Security config
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/", "/index", "/register", "/regitrationConfirm", "/forgotPassword", "/accountRecovery", "/passwordReset", "/public/**").permitAll()
.antMatchers(HttpMethod.POST, "/register", "/accountRecovery","/passwordReset").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginPage("/login?error")
.permitAll()
.failureHandler(authFailureHandler)
.and()
.rememberMe()
.tokenValiditySeconds(3600)
.key("rememberTracker")
.and()
.logout()
.permitAll()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired");
}
}
i want to redirect or show a custom page to the user if authorization fails. Is there a way to that?
updated with spring security code.
Thanks
I updated you SecurityConfig to add a failureUrl and successHandler
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/", "/index", "/register", "/regitrationConfirm", "/forgotPassword", "/accountRecovery", "/passwordReset", "/public/**").permitAll()
.antMatchers(HttpMethod.POST, "/register", "/accountRecovery","/passwordReset").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginPage("/login?error")
.permitAll()
.failureUrl("/your-unsuccessful-authentication-url-here")
.successHandler(yourSuccesshandler) //create your success handler to redirect the user to different places depending on his role
//.failureHandler(authFailureHandler) I deleted this line, we just need a redirect
.and()
.rememberMe()
.tokenValiditySeconds(3600)
.key("rememberTracker")
.and()
.logout()
.permitAll()
.logoutUrl("/logout")
.logoutSuccessUrl("/")
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/login?expired");
}
}
The success Handler
public class SuccessAuthenticationHandler implements AuthenticationSuccessHandler{
public SuccessAuthenticationHandler(){
}
#Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth) throws IOException, ServletException {
HttpSession session = request.getSession();
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String redirect = "";
if(user != null){
session.setAttribute("username", user.getUsername());
if(user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"))
|| user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_SUPER_ADMIN")))
redirect = "admin/";
else if(user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_YOUR_ROLE")))
redirect = "yourrole/";
}
if(redirect.isEmpty())
redirect = "signin";
response.sendRedirect(redirect);
}
}

Spring Boot Security Login

My enhanced Pet Clinic application requires security.
I want to have the following:
Login form - WORKING
HTTPS - WORKING
HTTP requests redirecting to HTTPS - not sure how to do this
HTTP static resources - not sure if this is really necessary
Any advice would be welcome.
My application can be found at https://github.com/arnaldop/enhanced-pet-clinic.
Here's code from my WebSecurityConfigurerAdapter subclass:
private static final String[] UNSECURED_RESOURCE_LIST =
new String[] {"/", "/resources/**", "/assets/**", "/css/**", "/webjars/**",
"/images/**", "/dandelion-assets/**", "/unauthorized", "/error*"};
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(UNSECURED_RESOURCE_LIST);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
//#formatter:off
http
.authorizeRequests()
.antMatchers(UNSECURED_RESOURCE_LIST)
.permitAll()
.antMatchers("/owners/**", "/vets/**", "/vets*").hasRole("USER")
.antMatchers("/manage/**").hasRole("ADMIN")
.anyRequest()
.permitAll()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID")
.permitAll()
.and()
.requiresChannel()
.antMatchers("/login", "/owners/**", "/vets/**", "/vets*", "/manage/**")
.requiresSecure()
.and()
.exceptionHandling()
.accessDeniedPage("/router?q=unauthorized")
.and()
.sessionManagement()
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.expiredUrl("/login?expired")
;
//#formatter:on
}
Thanks!
For "HTTP requests redirecting to HTTPS - not sure how to do this"
we will need to add the TomcatEmbeddedServletContainerFactory bean to one of our #Configuration classes.
#Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
#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);
}
};
tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
for more information please refer this link

Resources