How to configure OAuth2ResourceServer and OAuth2Client in the same application?

1.6k views Asked by At

My application consists of an Angular UI, and a Spring backend. Both are bundled together and deployed on the same server. I am new to Spring Security/Oauth2, I find it very confusing. I want will be exposing a few APIs which could be consumed either from the UI or from Postman/Swagger.I have successfully configured OAuth2ResourceServer of Spring security 5 for this and it works perfectly fine. When I call the API with a bearer token, it works as expected.

http.requestMatchers().antMatchers("/api/**")
    .and().authorizeRequests().anyRequest().authenticated()
    .and().oauth2ResourceServer().jwt(); 

Now, I also have to configure the same for when the API calls are made from the UI. This is very confusing. I have tried to create a separate http config as follows;

http.antMatcher("/**").authorizeRequests()
        .antMatchers("/").permitAll()
        .anyRequest().authenticated()
        .and()
        .oauth2Login();
...
...

I don't really know how to proceed. I have configured clientid, clientSecret, authorization-grant-type, redirect-uri, scope, authorization-uri, token-uri in the application.properties file. The expectation is to prompt a user with a centralised login page, and somehow exchange the grant_code for an access token(jwt). All requests from the UI must contain this token in its header to access the API, which I have described above (Resource Server config). Again, I am confused as to store the token in header or a cookie.

Apologies if I am not clear. My understanding of OAuth2 is very basic, I am trying to read through pages of documentation, it is making little sense to me.

1

There are 1 answers

0
Bijesh CHandran On

you can keep your backend as a oauth2 resource server ( as it is now) and then configure your frontend as an oAuth2 public client. You can use angular keycloak library for this. It will be then the responsiblity of the frontend code to get access token from your ID and then set it in the request header of each api call to your resource server.