Why am I redirected directly to login page instead of index.html in Spring? - spring

I am learning to design a login page in Spring Boot. I have not created any file named login, instead I have created an index page but by default it is redirecting me to login page?
package com.main.medipp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#SuppressWarnings("deprecation")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Bean
public UserDetailsService userDetailsService() {
return (UserDetailsService) new CustomUserDetailsService();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/sign_up").permitAll()
.antMatchers("/users").authenticated()
.anyRequest().permitAll()
.and()
.formLogin()
.usernameParameter("email")
.defaultSuccessUrl("/users")
.permitAll()
.and()
.logout().logoutSuccessUrl("/").permitAll();
}
}
This is the code , i used , please help me with what changes should i make now!!

If you have secured your / endpoint, you will get redirected to the default login page. To fix that, add a rule to the / endpoint to disable authentication and redirect to the index page via a Controller.

Related

Adding WebSecurityConfig causes a 404 error

When I add in my websecurityconfig file, I get a 404 error. My Websecurityconfig looks like the following. What is annoying is this works locally but not when deployed. I try to hit the head of my application which I would expect to redirect to the login page but it 404's before logging in
package org.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.example.demo.LoginSuccessHandler;
import javax.sql.DataSource;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Bean
public UserDetailsService userDetailsService() {
return new CustomUserDetailsService();
}
#Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService());
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/abc").hasAnyAuthority("ROLE_one")
.antMatchers("/def").hasAnyAuthority("ROLE_one")
.antMatchers("/ghi").hasAnyAuthority("ROLE_one")
.antMatchers("/jkl").hasAnyAuthority("ROLE_one")
.antMatchers("/mno").hasAnyAuthority("ROLE_one")
.antMatchers("/pqr").hasAnyAuthority("ROLE_one")
.antMatchers("/stu").hasAnyAuthority("ROLE_two")
.antMatchers("/vwx").hasAnyAuthority( "ROLE_two")
.antMatchers("/yza").hasAnyAuthority("ROLE_two")
.antMatchers("/bcd").hasAnyAuthority("ROLE_two")
.antMatchers("/").permitAll()
.and().formLogin()
.successHandler(successHandler)
.and().logout().permitAll();
}
#Autowired private LoginSuccessHandler successHandler;
}
I have tried removing it which gets rid of the 404 error but I need the security to be set up.
A 404 means no page has been found for the url you are trying to access. You have the below setting for your HttpSecurity, meaning anyone can access the root of your application and it looks like no page or index.html is defined for it -
.antMatchers("/").permitAll()
Do you have a different package you deploy and locally you have the a page defined for root url which is why you do not see a 404?
turns out I did not have my application.properties file filled out correctly to connect with my database. fixing that fixed the error.
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto=create
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/<application_name>
spring.datasource.username=<username>
spring.datasource.password=<password>
and I needed to use Controller and not RestController everywhere

Spring Basic Auth not working using BCrypt Encoding - I am getting redirected to login popup again even after entering correct credentials

Below is my PasswordEncoder Class
package com.example.springsecuritybasic.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
#Configuration
public class PasswordConfig {
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Below is my ApplicationSecurityConfig Class
package com.example.springsecuritybasic.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
#Configuration
#EnableWebSecurity
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter{
private final PasswordEncoder passwordEncoder;
#Autowired
public ApplicationSecurityConfig(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","index","/css/*","/js/*")
.permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected UserDetailsService userDetailsService() {
UserDetails annasmithUser = User.builder()
.username("anna")
.password(passwordEncoder.encode("password"))
.roles("STUDENT")
.build();
return new InMemoryUserDetailsManager(
annasmithUser
);
}
}
Below is my Main Class -
package com.example.springsecuritybasic;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringsecuritybasicApplication {
public static void main(String[] args) {
SpringApplication.run(SpringsecuritybasicApplication.class, args);
}
}
From the WebSecurityConfigurerAdapter#userDetailsService Javadoc:
Allows modifying and accessing the UserDetailsService from userDetailsServiceBean() without interacting with the ApplicationContext. Developers should override this method when changing the instance of userDetailsServiceBean().
To configure a custom user, you can register a UserDetailsService bean rather than overriding the method
#Bean
protected UserDetailsService userDetailsService() {
UserDetails annasmithUser = User.builder()
.username("anna")
.password(this.passwordEncoder.encode("password"))
.roles("STUDENT")
.build();
return new InMemoryUserDetailsManager(
annasmithUser
);
}

Spring boot security - cannot add role and authorities together for inMemoryAuthentication

This is my Configuration class, where is register the users and the url matchers.
package com.example.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin"))
.authorities("API_TEST1","API_TEST2")
.roles("ADMIN")
.and().withUser("test")
.password(passwordEncoder().encode("test1234"))
.authorities("API_TEST1")
.roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/api/test1").hasAuthority("API_TEST1")
.antMatchers("/api/test2").hasAuthority("API_TEST2")
.and().httpBasic();
}
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
}
For some reason the roles and authorities do not work together, they work when I disable one of them:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin"))
.authorities("API_TEST1","API_TEST2")
.roles("ADMIN")
.and().withUser("test")
.password(passwordEncoder().encode("test1234"))
.authorities("API_TEST1")
.roles("USER");
}
When I login with admin, admin I can enter the /admin section, but entering the api (api/test1 or api/test2) gives me a 403 error, while I should be able to enter both.
Here is my complete project:
https://github.com/douma/spring-security-exp

org.springframework.security.access.AccessDeniedException: Access is denied

I'm trying to implement OAuth in my spring boot rest server. Here's my configurations
configuration\AuthorizationServerConfig.java
package com.vcomm.server.configuration;
import com.vcomm.server.service.util.CustomAuthenticationKeyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import javax.annotation.Resource;
import javax.sql.DataSource;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Resource(name = "roomUserDetailsService")
UserDetailsService userDetailsService;
#Autowired
private DataSource dataSource;
#Bean
public TokenStore tokenStore() {
JdbcTokenStore tokenStore = new JdbcTokenStore(dataSource);
tokenStore.setAuthenticationKeyGenerator(new CustomAuthenticationKeyGenerator());
return tokenStore;
}
#Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
defaultTokenServices.setSupportRefreshToken(true);
defaultTokenServices.setAuthenticationManager(authenticationManager);
return defaultTokenServices;
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.pathMapping("/oauth/authorize", Constant.AUTH_V1 + "/oauth/authorize")
.pathMapping("/oauth/check_token", Constant.AUTH_V1 + "/oauth/check_token")
.pathMapping("/oauth/confirm_access", Constant.AUTH_V1 + "/auth/v1/oauth/confirm_access")
.pathMapping("/oauth/error", Constant.AUTH_V1 + "/oauth/error")
.pathMapping("/oauth/token", Constant.AUTH_V1 + "/oauth/token")
.pathMapping("/oauth/token_key", Constant.AUTH_V1 + "/oauth/token_key")
.tokenStore(tokenStore())
.userDetailsService(userDetailsService)
.authenticationManager(authenticationManager);
}
#EventListener
public void authSuccessEventListener(AuthenticationSuccessEvent authorizedEvent){
// write custom code here for login success audit
System.out.println("User Oauth2 login success");
System.out.println("This is success event : "+authorizedEvent.getSource());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
oauthServer.allowFormAuthenticationForClients();
}
}
configuration\ResourceServerConfig.java
package com.vcomm.server.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
#Autowired
TokenStore tokenStore;
#Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServicesResourceServer());
}
#Autowired
private AuthenticationManager authenticationManager;
#Bean
public DefaultTokenServices tokenServicesResourceServer() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore);
defaultTokenServices.setAuthenticationManager(authenticationManager);
return defaultTokenServices;
}
}
configuration\SpringWebSecurityConfig.java
package com.vcomm.server.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Configuration
#Order(1001)
public static class superAdminWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "emUserDetailsService")
UserDetailsService emUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.maximumSessions(2)
.maxSessionsPreventsLogin(true);
http
.csrf().disable();
http
.httpBasic()
.disable();
http
.authorizeRequests()
.antMatchers("/superadmin/api/v1/login")
.permitAll();
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/superadmin/api/v1/logout", "POST"))
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT))
.invalidateHttpSession(true);
http
.antMatcher("/superadmin/**")
.authorizeRequests()
.antMatchers("/superadmin/**").hasAuthority("ADMIN_PRIVILEGE");
}
#Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
#Bean
#Primary
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean(name = "emAuthenticationProvider")
public AuthenticationProvider emAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsService(emUserDetailsService);
return provider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(emUserDetailsService);
auth.authenticationProvider(emAuthenticationProvider());
}
}
#Configuration
#Order(1002)
public static class adminWebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.maximumSessions(2)
.maxSessionsPreventsLogin(true);
http
.csrf().disable();
http
.httpBasic()
.disable();
http
.authorizeRequests()
.antMatchers("/admin/api/v1/login")
.permitAll();
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/admin/api/v1/logout", "POST"))
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT))
.invalidateHttpSession(true);
http
.antMatcher("/admin/**")
.authorizeRequests()
.antMatchers("/admin/**").hasAuthority("ORGANISATION_PRIVILEGE");
}
}
#Configuration
#Order(1003)
public static class appWebSecurityConfig extends WebSecurityConfigurerAdapter{
#Resource(name = "roomUserDetailsService")
UserDetailsService roomUserDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.maximumSessions(2)
.maxSessionsPreventsLogin(true);
http
.csrf().disable();
http
.httpBasic()
.disable();
http
.authorizeRequests()
.antMatchers("/api/v1/*/login")
.permitAll();
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/api/v1/logout", "POST"))
.deleteCookies("JSESSIONID")
.logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> httpServletResponse.setStatus(HttpServletResponse.SC_NO_CONTENT))
.invalidateHttpSession(true);
http
.antMatcher("/api/**")
.authorizeRequests()
.antMatchers("/api/**").hasAuthority("ROOM_PRIVILEGE");
}
#Bean(name = "roomPasswordEncoder")
public PasswordEncoder roomPasswordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
#Bean(name = "roomAuthenticationManager")
public AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManagerBean();
}
#Bean(name = "roomAuthenticationProvider")
public AuthenticationProvider roomAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(roomPasswordEncoder());
provider.setUserDetailsService(roomUserDetailsService);
return provider;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(roomUserDetailsService);
auth.authenticationProvider(roomAuthenticationProvider());
}
}
}
While calling http://localhost:5524/auth/v1/oauth/authorize?client_id=clientapp&response_type=code&scope=read
I got this response
{
"timestamp": 1582545217836,
"status": 401,
"error": "Unauthorized",
"message": "Unauthorized",
"path": "/auth/v1/oauth/authorize"
}
I'm using jdbc to manage state of oauth here's my oauth table data
+-----------+--------------+---------------+-------+-------------------------------------------+-------------------------+-------------+-----------------------+------------------------+
| client_id | resource_ids | client_secret | scope | authorized_grant_types | web_server_redirect_uri | authorities | access_token_validity | refresh_token_validity |
+-----------+--------------+---------------+-------+-------------------------------------------+-------------------------+-------------+-----------------------+------------------------+
| clientapp | NULL | secret | read | password,authorization_code,refresh_token | http://localhost:8081/ | room | 36000 | 36000 |
+-----------+--------------+---------------+-------+-------------------------------------------+-------------------------+-------------+-----------------------+------------------------+
I think this error log is enough to answer this question because I'm new to spring boot.
If need additional information please ask through commants
It was my misunderstanding OAuth workflow. While calling this URL it's trying to authenticate me before grant. But postman showed just 401 instead of giving a redirect response. Calling it via a browser will redirect me to the login page for authentication.
Posting this answer to help guys new to OAuth and spring boot :)

Spring boot Security URL Configuration

I have set the root path as:-
server.contextPath=/myspringBootApp (in Application.propertes) file.
and changed the configuration file as:-
package com.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public CustomAuthenticationEntryPoint unauthorizedHandler;
#Autowired
MyDaoAuthenticationProvider authProvider;
#Bean
public CustomAuthenticationTokenFilter authenticationTokenFilterBean() {
return new CustomAuthenticationTokenFilter();
}
#Autowired
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider.authProvider());
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.authorizeRequests()
// UI related urls
.antMatchers(
HttpMethod.GET,
"/",
"/myspringBootApp/login",
"/content/**",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/assets/**"
).permitAll()
//Back end - auth layer
.antMatchers("/auth/user").permitAll()
//Back end - actual rest layer
.antMatchers(HttpMethod.POST,"/auth/login").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
httpSecurity.addFilterBefore(authenticationTokenFilterBean(),UsernamePasswordAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
The above code is not working and loading the UI. I tried changing the UI URLs to /myspringBootApp/favicon.ico, but this also dint give desired result.
Can anyone help me to find a solution?
I think you can use the WebSecurity part of the WebSecurityConfigurerAdapter for this:
#Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/")
.antMatchers("/favicon.ico")
.antMatchers("/**.css")
.antMatchers("/webjars/**")
...

Resources