custom login page for spring security oauth2 client login - spring-boot

I'm trying to implement social login in my spring boot 2 app with a custom login page. I place spring-boot-starter-oauth2-client as a dependency in my pom.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
I then provide some client id and secret details in my application properties file..
spring.security.oauth2.client.registration.google.client-id=client-id
spring.security.oauth2.client.registration.google.client-secret=client-secret
With this minimal code spring boot registers the client and provides a login page with a link to login via the client. Now I want to provide my own login page so I have created a Seurity config..
#Configuration
#EnableWebSecurity(debug = false)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth/**", "/login/oauth2/**", "/login**", "/logout", "/**/*.css", "/**/*.js").permitAll()
.anyRequest().authenticated()
.and()
.oauth2Login().loginPage("/login")
.and()
.logout();
}
}
I then provide a controller to serve up my custom login page, I have just put this in my spring boot config for now..
#SpringBootApplication
#Controller
public class SingleSignonApplication {
public static void main(String[] args) {
SpringApplication.run(SingleSignonApplication.class, args);
}
#RequestMapping("/login")
public String loginPage() {
return "login.html";
}
}
..and my login page (simplified) provides links to login via google..
<a class="btn btn-block btn-social btn-google" href="/oauth2/authorization/google"><span class="fab fa-google"></span> Sign in with Google</a>
Now when I sign in via this button, it calls google, is authenticated and then when its redirected to login/oauth2/code/google... I get a 404 page not found. Also /logout stops working. Do I need to manually configure the other stuff as I realise I am relying on spring boot to continue setting up the clients listed in the app propertie file and set up a client repository automatically.

Related

How to secure only swagger UI page " swagger-ui/index.html#/ " and all other API end points should not be authenticated in Spring boot

I have a requirement where I just need to secure the Swagger UI page. All other endpoints I have written in the application should not be authenticated.
For this, I am using the Spring security starter. I have the Security Config for Spring boot in place. I am trying to authenticate ("/v2/api-docs") because this is where we see all the endpoints in Swagger UI. And also I am trying to permit ("/calculator-controller/callCalculatorServiceUsingPOST") which I see in browser URL when I click on my end point Try it now button and also permitting ("/calculate") which is in my controller. To be safer, I have tried to permit all possible combinations, but no luck.
What Am I missing ???
#Configuration #EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.authorizeRequests()
.antMatchers("/v2/api-docs").authenticated()
.antMatchers("/calculator-
controller/callCalculatorServiceUsingPOST",
"calculator-controller/**", "/calculate")
.permitAll()
.and()
.httpBasic();
}
}

Spring Security redirecting custom login page to itself - Too Many Redirects

I'm currently developing a custom login-page for my Spring Boot Application but I just can't get it to work. Using the default one works fine but as soon as I try to use my custom file, it just repeatedly redirects me until my Browser give up.
Other posts suggest permitting access to the login-path to erveryone but this also doesn't seem to work.
Here is my code:
WebSecurityConfig
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
And Controller for login-page
#Controller
public class WebController {
#GetMapping("/login")
public String login () {
return "login";
}
}
Any ideas what I'm missing?
You are probably using a lot of CSS and JS file link links, according to your code Spring Boot must first authenticate all the links, which is why it redirects to your login page many times.
add following code to bypass security authentication of resource link
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/bower_components/**", "/dist/**", "/plugins/**"); //write your resource directory name
}

How to get UserGroups from KeyCloak and print them in Java

I have a spring-boot application which uses spring-boot-starter-security and I have integrated Keycloak to Spring Boot application for authentication / authorization purposes. I want to fetch UserGroups from KeyCloak and display them in my SpringBoot Application. Do you know a way to fetch UserGroups from KeyCloak and display them at screen? There should be an implementation to provide it ?
This is my SecurityConfiguration java :
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#EnableWebSecurity
public class KeyCloakSecurityConfig extends WebSecurityConfigurerAdapter {
private final KeycloakJwtConfig keycloakJwtConfig;
#Override
public void configure(final HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable()
.formLogin().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/actuator/health").permitAll()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(new JwtAuthoritiesExtractor())
.jwkSetUri(this.keycloakJwtConfig.jwkSetUri());
}
#Autowired
public SecurityConfiguration(final KeycloakJwtConfig keycloakJwtConfig) {
keycloakJwtConfig = keycloakJwtConfig;
}
For listing all user groups within a Keycloak realm in Java, you may use Keycloak Admin REST client library provided with Keycloak and available in public Maven repositories: groupId=org.keycloak, artifactId=keycloak-admin-client, version is/should be the same as your Keycloak server (at least the same major and minor parts). Basically, with this library, you create a Keycloak instance, then select the realm, and get the groups from there, e.g. as shown in the Server Developer guide, section Admin REST API > Example using Java and the GroupTest test case on Keycloak github (method searchAndCountGroups).
Keycloak keycloak = Keycloak.getInstance(
"http://localhost:8080/auth",
"master",
"admin",
"password",
"admin-cli");
RealmRepresentation realm = keycloak.realm("master").toRepresentation();
for (GroupRepresentation group : realm.groups().groups())
{
// Display group.getId(), group.getName(), etc.
}

Spring Security - Redirect to custom login page without going through controller

I am currently using Spring Boot + Spring Security to develop a simple website that need user to login to access it. I have created my own custom static login page under resources/templates1/bruceLogin1.html. Any unathenticated access to my website to first be redirected to the login page URL which is http://localhost:8080/templates1/bruceLogin1.html
Note: that I am NOT creating any controller for this login URL, hence I am expecting the bruceLogin1.html to be accessed directly bypassing controller. Because i directly allow access to this html page without going thru controller, I assume no view resolver (e.g thymleaf) is required.
I open my browser, and enter http://localhost:8080/blablabl, and browser redirect me to http://localhost:8080/templates1/bruceLogin1.html , but sadly, i got error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Jan 11 12:40:37 SGT 2020
There was an unexpected error (type=Not Found, status=404).
No message available
Below is my configuration,
#SpringBootApplication
#EnableWebSecurity
public class SpringSecurityCatalogApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(SpringSecurityCatalogApplication.class, args);
}
#EnableWebSecurity
#Order(Ordered.HIGHEST_PRECEDENCE)
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/templates1/bruceLogin1.html")
.permitAll();
}
}
}
Think instead of putting under resources/template1 folder, i will just put the custom login page into either resources/static or resources/public folder.
Then configure as shown below
#EnableWebSecurity
#Order(Ordered.HIGHEST_PRECEDENCE)
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/bruceLogin1.html")
.permitAll();
}
}
Open browser and access any URL, you will be redirected to http://localhost:8080/bruceLogin1.html. And thats it!
Note that this does not require any controller nor view resolver.

How to redirect using spring security session time out?

I'm using spring boot 2.2.0.M2 spring security this package version is 5.2.0, my project fronted is done in vuejs 2.6.10
What I want to archive seems very simple, when spring security session is time out i want to redirect ( force browser ) to go to URL http://localhost:8080/
What I was trying till now is:
I have created configuration class:
#Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.formLogin()
.loginPage("/")
.defaultSuccessUrl("/admin#/timetable")
.permitAll()
.and().logout()
.logoutSuccessUrl("/")
.permitAll()
.and()
.sessionManagement()
.maximumSessions(1)
.expiredUrl("/")
.expiredSessionStrategy(event -> event.getResponse().sendRedirect("/"));
// this supoose to work right?
}
}
and in my application.properties I have added for testing purpouses:
# Server
server.servlet.session.timeout=1m
And after one minute nothing happens.
So I thought that maybe something is wrong and session is not timeout so I've run my application in debug mode and I putted break point in
package org.springframework.security.web.session;
...
public class HttpSessionEventPublisher implements HttpSessionListener
{
...
public void sessionDestroyed(HttpSessionEvent event) {
//my break point
}
}
And after one minute I'm in, debugger stopped in sessionDestroyed method so session is no longer exist.
About my UI, I'm using vuejs embedded in thyme leaf page:
So my question is do You know how to force browser to reload my application or redirect to http://localhost:8080/ when spring security session is expired (timeout) ?

Resources