Spring Security Java Config same url allowed for anonymous user and for others authentication needed - spring

In Spring Security Java Config
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/guest/**").authenticated;
}
What if I want this same url to be allowed access to a particular principal or a User.
And others Authentication needed. Is it possible?

If you want to completely bypass any security checks for certain URLs, you could do the following:
#Override
public void configure(WebSecurity web) throws Exception {
// configuring here URLs for which security filters
// will be disabled (this is equivalent to using
// security="none")
web
.ignoring()
.antMatchers(
"/guest/**"
)
;
}
This is equivalent to the following XML snippet:
<sec:http security="none" pattern="/guest/**" />

Two approaches; first, use HttpSecurity#not() like this to block anonymous users;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/guest/**")
.not().hasRole("ANONYMOUS");
// more config
}
Or use something like ROLE_VIEW_GUEST_PAGES that gets added depending on the user type from your UserDetailsService. This, IMO gives you better control over who sees guest pages.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/guest/**")
.hasRole("VIEW_GUEST_PAGES");
// more config
}

Related

Avoid oauth authentication for specific endpoints: Spring boot oAuth2

I am quite new to Spring boot OAuth. My application is using OAuth2 integrated with Azure AD. I want to have a URL which will not redirect to Azure AD for authentication. It was quite straight forward with Spring Security, we could configure something like this:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/someURL");
}
Is there an alternative available for OAuth?
Yes can allow access to everyone by using this
#Override
public void configure(HttpSecurity http) throws Exception {
http.antMatchers("/someURL").permitAll();
}
for details check.
You can avoid specific end point authentication like below
#Override
public void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/url/**").permitAll()
.anyRequest().authenticated();
}

Spring security: How can I enable anonymous for some matchers, but disable that for the rest?

I am trying to enable the anonymous access to some part of my rest api, but disable that to the rest.
I tried config looks like:
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anonymous().and()
.antMatchers(SOME_URL).authenticated()
.and()
.anoymous().disable()
.antMatchers(OTHER_URL).authenticated();
}
But later, I realized that the later anonymous().disable will cover the previous setting.
So is anyone can give me some suggestion that how can I enable the anonymous for part of my url?
Many thanks!!!
You can define a RequestMatcher, one for public urls and other for protected urls. Then, override the configure method which accepts WebSecurity as param. In this method, you can configure web to ignore your public urls.
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
new AntPathRequestMatcher("/public/**")
);
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
#Override
public void configure(final WebSecurity web) {
web.ignoring().requestMatchers(PUBLIC_URLS);
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.anyRequest()
.authenticated();
// and other clauses you would like to add.
}

Spring Security with OAuth2 and anonymous access

I have my Spring REST API secured with Spring Security and OAuth2, I can successfully retrieve a token and access my APIs. My App defines the OAuth2 client itsself.
Now I want users to have anonymous access on some resources. The use case is really simple: I want my app to be usable without login - but if they are logged in, I want to have access to that principal.
Here is my WebSecurityConfigurerAdapter so far:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/api1").anonymous().and()
.authorizeRequests().antMatchers("/ap2**").permitAll();
}
As soon as I add a second antMatcher/anonymous, it fails to work though, and it doesn't really express my intent either - e.g. I wan't to have anonymous access on api1 GETs, but authenticated on POSTs (easy to do with #PreAuthorize).
How can I make the OAuth2 authentication optional?
I dropped my #EnableWebSecurity and used a ResourceServerConfigurerAdapter like so:
#Configuration
#EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/api1", "/api/api2").permitAll()
.and().authorizeRequests()
.anyRequest().authenticated();
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("my-resource-id");
}
}
/api/api1 may now be called with or without authentication.

Bad MIME type in connection with Spring Security

How can I prevent my application from this type of errors:
Refused to execute script from 'http://localhost:8091/inline.f65dd8c6e3cb256986d2.bundle.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
It's a Spring Boot app with Angular 4 and when I run first page it throws those errors.
errors
I think it could have connection with Spring Security becuase when I added:
.and().formLogin().loginPage("/")
.loginProcessingUrl("/").permitAll();
It started throwing errors, but I really need this piece of code. The whole method looks:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests()
.antMatchers("/resources/static/**/*", "/", "/api/auth").permitAll()
.anyRequest().authenticated()
.and().formLogin().loginPage("/")
.loginProcessingUrl("/").permitAll();
}
Assuming you are extending your security configuration class from WebSecurityConfigurerAdapter then you could make use of overriding protected void configure(WebSecurity web) throws Exception:
#Override
protected void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/inline.**") // or better ending with ".{js,html}" or something
.antMatchers("/resources/static/**/*");
}
This would allow all requests starting with /inline. and /resources/static/....

How to disable spring security for certain resource paths

I am implementing spring security in a spring boot application to perform JWT validation where I have a filter and an AuthenticationManager and an AuthenticationProvider. What I want to do is that I want to disable security for certain resource paths (make them unsecure basically).
What I have tried in my securityConfig class (that extends from WebSecuirtyConfigurerAdapater) is below:
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(),
UsernamePasswordAuthenticationFilter.class);
httpSecurity.authorizeRequests().antMatchers("/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
What I am trying to do right now is that I want to make all my resource paths to be un-secure,
but the above code doesn't work and my authenticate method in my CustomAuthenticationProvider (that extends from AuthenticationProvider) get executed every time
Authentication piece gets executed irrespective of using permitAll on every request. I have tried anyRequest too in place of antMatchers:
httpSecurity.authorizeRequests().anyRequest().permitAll();
Any help would be appreciated.
Override the following method in your class which extends WebSecuirtyConfigurerAdapater:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/unsecurePage");
}
try updating your code in order to allow requests for specific paths as below
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(),
UsernamePasswordAuthenticationFilter.class);
httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/exemptedPaths/").permitAll();
httpSecurity.csrf().disable();
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Resources