Spring Security returns 401 for unsecured URL - spring

Using Spring Security 4.0.3 from a Spring Boot 1.3.3 application.
The application has two types of HTTP contents : "API" a REST API and "UI" a web based used interface (Thymeleaf + Spring Web MVC).
Most endpoints of the REST API of the application are secured, using Basic, but some are not and should always be available.
The simplified configuration looks like:
// In one method, the security config for the "API"
httpSecurity
.antMatcher("/api/**")
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.authorizeRequests()
.antMatchers("/api/ping").permitAll()
.antMatchers("/api/**").hasRole("USER")
.and()
.httpBasic();
// In another method, the security config for the "UI"
httpSecurity
.authorizeRequests()
.antMatchers("/ui/", "/ui/index.html", "/ui/css/*", "/ui/js/*", "/ui/img/*").permitAll()
.antMatchers("/ui/user/**").hasRole("USER")
.antMatchers("/ui/**").denyAll()
.and()
.formLogin().loginPage("/ui/login.html").permitAll().failureUrl("/ui/login.html").defaultSuccessUrl("/ui/user/main.html")
.and()
.logout().logoutUrl("/ui/logout").permitAll().logoutSuccessUrl("/ui/login.html")
.and()
.httpBasic();
Accesses to secured endpoints work as expected.
But accesses to public endpoints such as ".../api/ping" fail with a 401 when the user provided an invalid Basic authentication. Of course such endpoints works fine when no or valid Basic authentication is provided.
This 401 from Spring Security is surprising. How can we implement a Spring Security configuration that never returns any 401 or 403 for selected endpoints?
Thank you for your time.
Update 1 : added info about the "UI" existence and security config

Order is important. Most specific rule (path) first:
httpSecurity
.antMatchers("/api/ping").permitAll()
// and then the rest
This because if there is a match like on antMatcher("/api/**"), Spring Security will not evaluate later rules.

Related

How to setup ForwardedHeaderFilter for login using Spring Security without Spring Boot?

I am looking to setup the ForwardedHeaderFilter in spring security so I can let spring know which protocol to use after login. I have several app servers behind a load-balancer (using ssl termination) and spring security is redirecting the user using http (instead of https). Because of this, my users are now getting a obtrusive warning message. The only examples I can find online are with spring boot which I do not implement.
I thought of using "addFilterBefore()" method to my security configuration, but the filter is never called.
Any ideas?
// Apply sameOrigin policy for iframe embeddings
http.headers().frameOptions().sameOrigin();
// ********* Add filter here? *******
http.addFilterBefore(new ForwardedHeaderFilter(), ChannelProcessingFilter.class);
// Authorization filters
http.authorizeRequests().antMatchers("/sysAdmin/**", "/monitoring/**").access("isFullyAuthenticated() and hasRole('GOD')");
http.authorizeRequests().antMatchers("/app/**").authenticated();
http.authorizeRequests().antMatchers("/**").permitAll();
http.formLogin()
.loginPage("/public/login.jsp")
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/app/Dashboard.action", false)
.failureHandler(customAuthenticationFailureHandler());
// Disable so that logout "get" url works (otherwise you have to do a html form)
http.csrf().disable();
http.logout().logoutSuccessUrl("/public/login.jsp");
http.sessionManagement()
.invalidSessionUrl("/public/expiredSession.jsp?expiredId=2")
.maximumSessions(2)
.sessionRegistry(sessionRegistry())
.expiredUrl("/public/expiredSession.jsp?expiredId=3");
I ended up adding the filter like this and everything seemed to work
// Added for load balancer headers (X-Forwarded-For, X-Forwarded-Proto, etc)
http.addFilterBefore(new ForwardedHeaderFilter(), WebAsyncManagerIntegrationFilter.class);

How do I use multiple 'JWK Set Uri' values in the same Spring Boot app?

I have a requirement to use two different authorization servers (two Okta instances) to validate authentication tokens coming from two different web applications inside a single Spring Boot application which is a back-end REST API layer.
Currently I have one resource server working with the following configuration:
#Configuration
#EnableWebSecurity
public class ResourceServerSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests().antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer().jwt();
}
}
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-X.okta.com/oauth2/default
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://dev-X.okta.com/oauth2/default/v1/keys
and with dependencies spring-security-oauth2-resource-server and spring-security-oauth2-jose in my Spring Boot app (version 2.2.4.RELEASE)
The end state I want to get into is, depending on a custom HTTP header set in the request, I want to pick which Okta instance my Spring Boot app uses to decode and validate the JWT token.
Ideally I would have two properties in my configuration file as follows:
jwkSetUri.X=https://dev-X.okta.com/oauth2/default/v1/keys
jwtIssuerUri.X=https://dev-X.okta.com/oauth2/default
jwkSetUri.Y=https://dev-Y.okta.com/oauth2/default/v1/keys
jwtIssuerUri.Y=https://dev-Y.okta.com/oauth2/default
I should be able to use a RequestHeaderRequestMatcher to match the header value in the security configuration. What I cannot workout is how to use two different oauth2ResourceServer instances that goes with the security configuration.
With spring boot this is not possible to do out of the box right now.
Spring Security 5.3 provides functionality to do this (spring boot 2.2.6 still doesn't support spring security 5.3).
Please see following issues:
https://github.com/spring-projects/spring-security/issues/7857
https://github.com/spring-projects/spring-security/pull/7887
It is possible to do manual configuration of resource server to use multiple identity providers, by following links that i have provided. Provided links are mainly for spring boot webflux development. For basic spring boot web development please see this video:
https://www.youtube.com/watch?v=ke13w8nab-k
This is possible as of Spring security 5.3+ using the JwtIssuerAuthenticationManagerResolver object
Override the configure(HttpSecurity http) inside your configuration class which extends WebSecurityConfigurerAdapter
JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver(
"http://localhost:8080/auth/realms/SpringBootKeyClock",
"https://accounts.google.com/o/oauth2/auth",
"https://<subdomain>.okta.com/oauth2/default"
);
http.cors()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**")
.hasAnyAuthority("SCOPE_email")
.antMatchers(HttpMethod.POST, "/api/foos")
.hasAuthority("SCOPE_profile")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer(oauth2 -> oauth2.authenticationManagerResolver(authenticationManagerResolver));

Receive Authorization header on anonymous url using Spring Boot

How can an Authorization header be accessed on anonymous urls?
My security configuration looks like:
http
.authorizeRequests()
.antMatchers("/login", "/legacy-login").anonymous()
.antMatchers("/things/*").authenticated()
.anyRequest().permitAll()
.and()
.httpBasic()
Authentication in general works fine. However, on /legacy-login I need to do some migration and need to access the authorization header without spring boot managing the authorization. Although /legacy-login is marked anonymous as soon as there are requests, spring intercepts the request and tries to authorize itself (what then results into 401).
How can I make Spring let the auth header through on that single url?
I foudn one solution myself. Instead of fiddleing around with .anonymous() and .permitAll() I added /legacy-login as ignore rule:
override fun configure(web: WebSecurity) {
super.configure(web)
web.ignoring()
.antMatchers("/legacy-login")
}

How to allow certain endpoint in spring security to be allowed without authentication?

I have Spring Boot Rest API web app in which I am using spring security to have most endpoints to require authentication.
This is part of code:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
....
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestMatchers()
.antMatchers("/oauth/token")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.anyRequest().authenticated();
}
Can some one explain what each line begining with http.csrf means?
How can I modify above code so that enpoint /bars/pk can be allowed to be accessed without requiring authentication just as if there was no Spring Security ?
By default, Spring Boot activates protection against CSRF attack (Cross Site Request Forgery attack). The attack consists of a malicious site taking advantage of a user being alredy authenticated to a site (e.g. bank) in order to trick the user to do actions on that site (e.g. fund transfer).
The protection against the attack consists of the Spring Boot application sending a token with every response and expecting the token to be sent by the client on subsequent request. If the token is not received, Spring Boot returns an error.
Sometimes, you want to disable this behavior (at your own risks), so you use csrf.disable. You might find it convenient to disable csrf protection if you develop a Stateless API, and you have no way to link a POST request to any previous requests or session. But again, you need to consider this and reason about it carefully.
Please note that CSRF protection has not effect on GET requests. It only affects state chaning requests (e.g. POST, DELETE)
In order to allow your endoints to anyone, without requiring any authentication, you need to use
http.authorizeRequests().antMatchers("/**").permitAll();
EDIT
To specifically allow unauthorized requests to /bars/pk and keep the other elements unchanged, modify your code as follows :
http.csrf().disable()
.requestMatchers()
.antMatchers("/oauth/token")
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/bars/pk").permitAll()
.anyRequest().authenticated();
Here is a complete example:
httpSecurity.authorizeRequests()
.antMatchers(HttpMethod.GET)
.permitAll() // Allow all GET requests to go unauthenticated
.antMatchers(allowedResources)
.permitAll() // Allow all requests to go unauthenticated for the specified paths
.antMatchers(protectedResources).hasRole(USER)
.antMatchers(adminResources).hasRole(ADMIN)
.anyRequest().authenticated(); // Authenticate all other request paths

Using SAML with Spring Boot behind an ELB redirects to http instead of https

I'm trying to use Okta to authenticate users from a SpringBoot application.
I've setup the app following the Okta Tutorial from : https://developer.okta.com/blog/2017/03/16/spring-boot-saml
However my app is behind an ELB, and as such the TLS is being terminated at the LB. So I've modified the configuration from the tutorial to suit my needs.
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/saml*").permitAll()
.anyRequest().authenticated()
.and()
.apply(saml())
.serviceProvider()
.keyStore()
.storeFilePath(this.keyStoreFilePath)
.password(this.password)
.keyname(this.keyAlias)
.keyPassword(this.password)
.and()
.protocol("https")
.hostname(String.format("%s", serverName))
.basePath("/")
.and()
.identityProvider()
.metadataFilePath(this.metadataUrl);
}
This does the trick but there is a problem. After the user is authenticated by Okta, the user is finally redirected to a http URL instead of a https URL. I am thinking the reason for this is that the TLS is being terminated at the LB and my app is actually receiving the request with http which is being sent in the RelayState.
This is something I found : spring-boot-security-saml-config-options.md.
It contains a list of SAML properties for spring boot security. I added the following to the application.properties file
saml.sso.context-provider.lb.enabled = true
saml.sso.context-provider.lb.scheme=https
saml.sso.profile-options.relay-state=<https://my.website.com>
It doesn't change the http redirection. Is there something I am doing wrong?
When a SAML 2.0 IdP like Okta redirects back to you application the endpoint url is either based on the SAML 2.0 metadata you application expose or the configuration in the IdP.
Furthermore, it is optional to add a Destination property in SAML 2.0 AuthnRequest:
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
Destination="https://my.website.com" IssueInstant="2018-11-22T09:23:08.844Z" Version="2.0" ID="id-f8ee3ab1-6745-42d5-b00f-7845b97fe953">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion"> ... </Issuer>
...
</samlp:AuthnRequest>

Resources