An unwanted default login interface appears - spring-boot

I started a Springboot application looking to create a login/registration Webapp .
I only set up Thymeleaf and Bootstrap for the HTML template , and set up the service, the controller and the repository.
This is the first time this login interface shows and whenever I change the URL it goes back to localhost:8080/login
I made sure that the port is set on the current project, and that there is no request set for /login
It looks like there is a backend set up for it and I do not undrestand from where it is ...

This is from Springboot security auto configuration , I had to disable it manually adding a configurating class :
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity security) throws Exception
{
//security.httpBasic().disable(); // Did work only for GET
security.csrf().disable().authorizeRequests().anyRequest().permitAll(); // Works for GET, POST, PUT, DELETE
}
}

Related

Reason for #EnableWebSecurity in the configuration class

I just read answer from the another question What is the use of #EnableWebSecurity in Spring?, but i couldn't understand why we need to add #EnableWebSecurity annotation at all.
Even I remove the #EnableWebSecurity from the configuration, my application still works.
Let's assume that we are going to implement either JWT based (rest api) or simply login based mvc application. For the following configuration what i am missing?
#Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Bean
public UserDetailsService userDetailsService() {
return new MyCustomUserDetailsService();
}
#Bean
public PasswsordEncoder passwsordEncoder() {
return new BrcyptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// for the jwt authentication add jwt filter etc ..
// for the login based, override default login page, error page etc..
}
}
If you are not using spring-boot but just a pure spring project , you definitely need to add #EnableWebSecurity in order to enable spring-security.
But if you are using spring-boot 2.0 +, you do not need to add it by yourself because the spring-boot auto configuration will automatically do it for you if you forget to do so. Under the cover , it is done by the WebSecurityEnablerConfiguration which its javadoc also states this behaviour as follows:
If there is a bean of type WebSecurityConfigurerAdapter, this adds the
#EnableWebSecurity annotation. This will
make sure that the annotation is present with default security
auto-configuration and also if the user adds custom security and
forgets to add the annotation.

Request Attribute not found after Spring Security added to Spring Boot app

I have a Spring Boot application that is running. As soon as I added Spring Security, the app generated an error.
I have a form that is backed by a bean. When I enable Spring Security, the bean for the form cannot be found. Before I added Spring Security, the bean and form worked.
The error that I receive after making a GET request to the form is
Neither BindingResult nor plain target object for bean name 'orderActive' available as request attribute
The form is using the ThymeLeaf package.
Spring Security Configuration
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("buzz")
.password("{noop}infinity")
.authorities("ROLE_USER");
}
}
Controller Method
#GetMapping("/orders/current")
public String orderForm() {
return "orderForm";
}
Test Class Annotations
#SpringBootTest
#AutoConfigureMockMvc
class DesignTacoControllerTest {
Test Method
#WithMockUser("buzz")
#Test
public void testProcessDesignGet() throws Exception {
mockMvc.perform(get("/orders/current")
.requestAttr("orderActive", new Order()))
.andExpect(status().isOk());
}
orderForm
<form method="POST" th:action="#{/orders}" th:object="${orderActive}">
I have tried adding a RequestAttribute to the controller method.
#GetMapping("/orders/current")
public String orderForm(#RequestAttribute("orderActive") Order orderActive) {
return "orderForm";
}
When I debug, the order has the same ID as the one that was added in the test method. The next step is to render the view. When I continue, the error appears.
Somewhere between the controller method and the view, the request parameter disappears. It has something to do with security, since the code runs without security enabled. The order form is found, so the page is not forbidden. Does security disable the request attributes?
You say it worked before Security, but, do you have a class (DTO) OrderForm with the fields you need in your form? I don't see one. If you don't create one and then add it to the model (that's the Binding part):
#GetMapping("/orders/current")
public String orderForm(Model model) {
model.addAttribute("orderForm", new OrderForm())
return "orderForm";
}

#EnableOAuth2Sso AND #EnableResourceServer in same app

I'd like have a set of services that can be used with "Client Credential" (for machine to machine) and with OAuth2 Single Sign On for the regular webapp (which is served by the same application).
I tried setting both #EnableOAuth2Sso and #EnableResourceServer; I expected to have the app "try" the token based and then fall back to SSO redirect in case it doesn't find any and the user does not have a session.
Each config works fine on its own (with a:
#Bean
public RemoteTokenServices ...
for #EnableResourceServer to configure the "CheckTokenEndpointUrl").
But as soon as I try with both I get:
APPLICATION FAILED TO START
Description:
Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a single bean, but 2 were found:
- userInfoTokenServices: defined by method 'userInfoTokenServices' in class path resource [org/springframework/boot/autoconfigure/security/oauth2/resource/ResourceServerTokenServicesConfiguration$RemoteTokenServicesConfiguration$UserInfoTokenServicesConfiguration.class]
- remoteTokenServices: defined by method 'remoteTokenServices' in class path resource [my/CustomWebSecurityConfigurerAdapter.class]
In your spring boot application class use the #EnableOAuth2Sso annotation and in the configuration class use #EnableResourceServer annotation and in this class define the endpoints to be used with access tokens.
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/user") //end point that needs access token in header
.antMatcher("/info") //end point that needs access token in header
.authorizeRequests().anyRequest().authenticated();
}
}
For more information refer the link

Spring OAuth Filter Chain & Java Config

I'm trying to add in spring-security-oauth to an existing app with spring-security. I'm using Java config.
I have an existing amended filter chain in place (with some custom filters added in) but requests to '/oauth/token' aren't using it, but are using the 'default' filter chain. How can i get access to the filter chain that's securing the oauth endpoints so that i can use the custom filters there also or can I wire in the OAuth endpoint(s) into the existing setup?
there is indeed a slightly smoother way using the interface AuthorizationServerConfigurer.
You can stick to the annotation #EnableAuthorizationServer and implement above interface in your configuration file. This will enable you to alter the oauth2-filter-chain by doing something like this:
#Configuration
#EnableWebSecurity
#EnableAuthorizationServer
public class SecurityConfig extends WebSecurityConfigurerAdapter
implements AuthorizationServerConfigurer
// some configuration ...
public void configure(AuthorizationServerSecurityConfigurer oauthSecurity) throws Exception {
oauthSecurity.addTokenEndpointAuthenticationFilter(new YourFilter());
}
// more configuration ...
}
In contrast to the addFilterXYX-methods of HttpSecurity you have no fine-grained influence here where the filter will be positioned in the filter chain. Any filter added by addTokenEndpointAuthenticationFilter will be inserted before the BasicAuthenticationFilter.
If you need to control the position of you filter in a more detailed way you could create a bean extending AuthorizationServerConfigurerAdapter instead of using the annotation #EnableAuthorizationServer. I did not try that but I guess you could then extend AuthorizationServerSecurityConfigurationlike systemfreund suggested without having to specify #Order(-1) because only your custom configuration gets imported. Probably you would also have to #Import AuthorizationServerEndpointsConfigurationlike it is done in the convenience annotation #EnableAuthorizationServer.
It's probably not the best way to do it, but I did not manage to find a better approach. The idea is to provide a custom AuthorizationServerSecurityConfiguration instance and override the default instance which is #Imported via #EnableAuthorizationServer. We just need to make sure to add an #Order annotation with higher precendence than the default configuration:
#EnableAuthorizationServer
#Import(CustomSecurityConfig.class)
public class Application {
}
#Configuration
#Order(-1)
public class CustomSecurityConfig extends AuthorizationServerSecurityConfiguration {
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http); // do the default configuration first
http
.addFilterBefore(new MyFilter(), ...);
}
}

H2 database console spring boot Load denied by X-Frame-Options

I`m building a skeletal project for dev with spring 4 boot security and others.
Using H2 while attempting to log into the db console and manage my db i get the following error. The page is blank, with 4 bugs in firebug konsole :
Load denied by X-Frame-Options: http://localhost:8080/console
With links to
/header.jsp?jsessionid=f71207a702c9177e57208414721bbe93 does not permit framing.
/query.jsp?jsessionid=f71207a702c9177e57208414721bbe93 does not permit framing.
/help.jsp?jsessionid=f71207a702c9177e57208414721bbe93 does not permit framing.
/tables.do?jsessionid=f71207a702c9177e57208414721bbe93 does not permit framing.
I can test the connection from console level - its ok.
DB works fine, import.sql works fine, i can create user entities withing spring is starting up.
The configuration i am using is from (and it works on spring 3.2 with xml configuration)
spring boot default H2 jdbc connection (and H2 console)
Using :
spring-boot-starter-parent
1.1.4.RELEASE
It's also possible to simplify the answer from #chrosciu with this:
#Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
}
}
Added the code below to Application.java and for now it works, default on port 8082, starts with spring app. It doesn`t hit the spot but for dev purposes it is all ok.
#Bean
org.h2.tools.Server h2Server() {
Server server = new Server();
try {
server.runTool("-tcp");
server.runTool("-tcpAllowOthers");
} catch (Exception e) {
e.printStackTrace();
}
return server;
}
This worked for me:
#EnableWebSecurity
#Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().addHeaderWriter(
new XFrameOptionsHeaderWriter(
new WhiteListedAllowFromStrategy(Arrays.asList("localhost"))));
}
}
Of course contents of white list should be adjusted in case when application is running on something different than localhost.

Resources