angular + spring boot war - 403 on refresh - java

I am trying to deploy a war with spring boot and angular as single unit.
This works fine on first go but when I refresh page it shows 403 error.
Steps I used to create war:
angular build - ng build --prod --base-href=/ui/ --deploy-url=/ui/
I take out the content of dist and paste it in static folder of my spring boot application/
Spring security config has code:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/ui/**");
//super.configure(web);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/","/api/hello/**","/api/login").permitAll()
.anyRequest()
.authenticated()
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
}
final step is to create an endpoint that will load index.html
#GetMapping("/")
public String loadUI() {
return "forward:/ui/index.html";
}
Please help me how to fix this.

Related

How to permit all HTTP redirect in Java Spring boot security?

I am writing a Java Spring Boot application that incorporates the Spring Boot Security in my pom.xml. However, It works when I redirect from login to my /home. Though when I change the page again or do a simple ajax call, I get passed a 403 error. I believe it has to do with the security and that page not having the proper access. I am looking for the best way to solve this with still keep my security intake.
Java Security:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.successHandler(new CustomAuthenticationSuccessHandler()) // On authentication success custom handler
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
Java Success Handler:
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
String principal = authentication.getName();
System.out.println("Successful login: principal " + principal);
ADID = principal;
response.sendRedirect("/dashboard");
}
Error in Controller:
Error 403 : http://localhost:8080/edit/ajax/doesSomething
So the /dashboard is the first page I get to if the login is successful, then after that the client inputs some fields and is moved to another page that calls a different URL path. It fails I assume when it calls the other paths that are not /dashboard
Your problem is CSRF token. You can disable it in the security configure but it is better you use it. See this site for more information.
Try this ...
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().permitAll()
.and()
.formLogin()
.successHandler(new CustomAuthenticationSuccessHandler())
.and()
.logout().logoutRequestMatcher(new
AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
}
or disable CSRF as quick fix.
http.csrf().disable();
Add this in java security. This will permit requests to any endpoint or specified ones:
`
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**").antMatchers("/example/endpoint");
}
`
And you can also keep your
protected void configure(HttpSecurity http) throws Exception

Using Spring Boot 2 OAuth Client and Resourceserver in the same context

I'd like my spring boot application to serve a protected frontend, as well as being an API resource server for said frontend at the same time, but I can't get the oauth stuff working.
What I want is the spring boot application to return a 302 redirect to the oauth server (gitlab in my case) when the browser requests the index.html without a token, so the user is sent to the login form. But I also want that the API to return a 401 when the API is called without a token, as I think a 302 redirect to a login page is not very useful there.
In pseudo code:
if document_url == /index.html and token not valid
return 302 https//gitlab/loginpage
if document_url == /api/restcall and token not valid
return 401
server document_url
I am working with spring boot 2.1, regarding oauth my pom.xml contains
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
This is my naive try in the SecurityConfig
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().antMatchers("/index.html").authenticated()
.and()
.oauth2Login().loginPage("/oauth2/authorization/gitlab")
.and()
.authorizeRequests().antMatchers("/api/restcall").authenticated()
.and()
.oauth2ResourceServer().jwt();
}
}
Both configurations (oauth2Login and oauth2ResourceServer) work fine for themself. But as soon as I combine them the last one wins (so in the above example there would be no 302 and the browser would also see a 401 for the index.html). I presume they share some configuration objects so the last write wins.
Is there an (easy) way to get what I want? I know spring can do almost anything, but I would very much not to end up manually configuring a gazillion beans ...
Update:
I've made a minimal example (including #dur's suggestion) of my code here
You need to create multiple configurations and restrict them only to specific URL patterns using requestMatcher. Based on your example, your configurations should look like this:
SecurityConfigHTML
public class SecurityConfigHTML extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/index.html")
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.oauth2Login().loginPage("/oauth2/authorization/gitlab");
}
}
SecurityConfigAPI
public class SecurityConfigAPI extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers().antMatchers("/api/call")
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.oauth2ResourceServer().jwt();
}
}
SecurityConfigHTML
I think we should include /oauth2/** into the request matchers, otherwise the oauth2Login will not work.
404 http://localhost:8080/oauth2/authorization/gitlab
public class SecurityConfigHTML extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.requestMatchers().antMatchers("/index.html", "/oauth2/**")
.and()
.authorizeRequests()
.antMatchers("/oauth2/**").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login();
// #formatter:on
}
}

Java Spring Boot Security Class Configuration

My aim is to add security class to my Java project except paths like "api/public/*".
When I request in POSTMAN
http://localhost:8080/api/public/signup
with a json body, I get 401. Here's my security class which permits all matchers of api/public/*:
What am I missing?
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
// we don't need CSRF because our token is invulnerable
.cors()
.and()
.csrf().disable()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
// don't create session
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/public/**").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
JwtAuthorizationTokenFilter authenticationTokenFilter = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil);
httpSecurity
.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
// disable page caching
httpSecurity
.headers()
.frameOptions().sameOrigin() // required to set for H2 else H2 Console will be blank.
.cacheControl();
}
#Override
public void configure(WebSecurity web) throws Exception {
// AuthenticationTokenFilter will ignore the below paths
web
.ignoring()
.antMatchers("/api/public/*");
}
Mvn clean solved my problem. It seems build somehow stuck in a previous state.
mvn clean

folder mapping in spring boot to open images from url spring

I want to map local folder to localhost:8080 How can I achieve this.
I am using spring boot. have given permitall to public/pic folder.
how to open in browser like below.
http://localhost:8080/public/pic/default.jpg
above link gives 401 and asks for username and password.
using below code for security in spring
#Override
protected void configure (HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors().disable();
http.authorizeRequests()
.antMatchers("/public/pic/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.logout();
// #formatter:on
}
where should be the folder /public/pic in local system?
Try to add to your config
#Override
public void configure(WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers("/public/pic/**");
}

Trigger Spring Security Login on Secured Request?

Spring Security "will provide you with a login form"...https://docs.spring.io/spring-security/site/docs/current/guides/html5/hellomvc-javaconfig.html
So how can I trigger the built-in form on the secured requests?
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("admin").roles("ADMIN", "USER").and()
.withUser("guest").password("guest").roles("USER");
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/test").hasRole("ADMIN")
.antMatchers(HttpMethod.PUT,"/test/**").hasRole("ADMIN")
.antMatchers(HttpMethod.DELETE,"/test/**").hasRole("ADMIN")
.antMatchers(HttpMethod.PATCH,"/test/**").hasRole("ADMIN").and()
.formLogin()
.and()
.csrf().disable();
}
When I make a POST to "/test" without signing in, it is correctly prevented and secured, but I'd like Spring to trigger its login form when the request is made from my front-end. Especially without creation of an html file, or a /login Controller, which seems like this feature makes possible.

Categories

Resources