I am going through a spring security tutorial where I am trying to configure a basic security using the spring-boot-starter-security using the class like below
import org.springframework.beans.factory.annotation.Autowired;
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.password.NoOpPasswordEncoder;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/","/api/*").permitAll()
.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll()
.and().logout().permitAll();
}
#Autowired
public void ConfigureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
.withUser("user").password("password").roles("USER");
}
}
But when I try to use the page localhost:8080 or localhost:8080/api/hello?name=test, it's not asking for login and directly showing the requested page. please help me with the issue.
Code allows access without authentication for / and /api/*
http.authorizeRequests().antMatchers("/","/api/*").permitAll()
It restricts access without authentication to any requests which are not matched with above url
.anyRequest().authenticated()
Related
I have an application made in Spring + Vue js and I have questions regarding the exposure of endpoints on the web.
After I'm authenticated in the system, when for example I try to access localhost:8080/contracts he is bringing the response in JSON format on the screen, but I would like to block this exposure, even on account of data security.
How can I best control this? Do I do for Spring Security?
WebSecurityConfig.java
package br.com.braxxy.adm.brxmind.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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.builders.WebSecurity;
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.web.util.matcher.AntPathRequestMatcher;
import br.com.braxxy.pls.web.user.CustomUserDetailsService;
#Configuration
#EnableWebSecurity
#ComponentScan("br.com.braxxy.adm.brxmind.security")
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Autowired
CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler;
#Bean
public UserDetailsService mongoUserDetails() {
return new CustomUserDetailsService();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = mongoUserDetails();
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/img/**", "favicon.ico", "/materialize/**", "/style/**").permitAll()
.antMatchers(HttpMethod.GET, "/new-user").hasRole("ADMIN")
.antMatchers(HttpMethod.POST, "/new-user").hasRole("ADMIN")
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
.loginPage("/login").failureUrl("/login?error=true").usernameParameter("email")
.passwordParameter("password").and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").and().exceptionHandling();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/assets/css/**", "/assets/css/vendor/**", "/assets/fonts/**", "/assets/images/**", "/assets/js/**", "/assets/js/vendor/**", "/assets/js/ui/**", "/assets/js/pages/**");
}
}
[![Response API][1]][1]
I'm creating a spring application for a college project.
package com.sales.security;
import org.springframework.context.annotation.Bean;
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
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/showProducts.html", "/showOrders.html", "/showCustomers.html","/newOrder.html","/addProduct.html","/addCustomer.html")
.authenticated()
.and()
.formLogin();
}
private static final String ENCODED_PASSWORD = "$2y$12$i4Cl5SZgrPFItSz/G5cvTObf0sqzHszwwKMZ4pQeUlElY1BR7KxdO"; //password is "user" encrypted using BCrypt
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("user").password(ENCODED_PASSWORD).roles("USER");
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
I've taken the code from user TwiN at Java Spring Security - User.withDefaultPasswordEncoder() is deprecated?
I have changed the hash to be "user" and have confirmed it's definitely "user" using https://bcrypt-generator.com/
but no matter what now, the login page won't allow me to login and says that my login details are incorrect
here's what my application looks like after entering a username="user" and password ="user"
there are a lot of methods to implement security in spring i can't follow what you are doing but here's my github repo Spring Boot Security you can shange the branches to see diffrent ways to apply security, select the branche "in memory" its the semplest one.
Add below properties in application.properties
spring.security.user.name = user
spring.security.user.password = user
spring.security.user.roles = USER
OR
Add these to the current SecurityConfig class
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
I have some urls (one as of now) which I would like to allow for every users like registration and login urls. I only want to exclude any url path after register and secure or restrict any other urls.
Please refer the code below:
package com.travelplanner.rest.config;
//COPY
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
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.builders.WebSecurity;
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.User.UserBuilder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DataSource securityDataSource;
#Bean
public UserDetailsManager userDetailsManager() {
JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager();
jdbcUserDetailsManager.setDataSource(securityDataSource);
return jdbcUserDetailsManager;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(securityDataSource);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().httpBasic().and().csrf().disable()
.authorizeRequests().antMatchers("/register/**").permitAll();
}
}
It is a spring mvc rest in google app engine. I have used the above snippet and it says unauthorised even for the antmatchers. Please help! Thanks in advance.
It's probably the httpBasic() part which is requiring authentication. You should put specific instructions first and more general ones at last, so try with this:
http.cors().and().csrf().disable()
.authorizeRequests().antMatchers("api/users/register/user").permitAll()
.and()
.anyRequest().httpBasic();
This allows everyone to access "api/users/register/user", but requires http authentication for other URLs.
I have a spring MVC application and a remote OAuth2 authorization server. Remote server should be used to log on to the web and mobile application and also to authorize micro services. OAuth2 server for authorization works and when I directly call path for obtain tokens, that request returns access and refresh token correctly.
My problem is that I cannot configure HttpSecurity in a class that extends WebSecurityConfigurerAdapter in the web application, in order to enable logging form to stay in application and send request to remote OAuth2 using the password grunt type. So the loginProcessingUrl() should not be default j_spring_security_check, rather the path to the authorization server. I could not achieve that using addFilterBefore() in the http configuration.
My AuthorizationServerConfigurerAdapter class on the Oauth2 server application in Spring Boot looks like this:
package com.mydomain.oauth2.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
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.TokenStore;
#Configuration
#EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("userDetailsService")
private UserDetailsService userDetailsService;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private TokenStore tokenStore;
#Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure( AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("acme")
.secret("acmesecret")
.accessTokenValiditySeconds(3600)
.scopes("read", "write")
.redirectUris("http://localhost:8080/login")
.authorizedGrantTypes("password", "refresh_token")
.autoApprove(true)
.resourceIds("resource");
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
configurer.authenticationManager(authenticationManager);
configurer.userDetailsService(userDetailsService);
configurer.tokenStore(tokenStore);
}
}
My WebSecurityConfigurerAdapter class on a web application that was written in Spring not in Spring Boot looks like this:
import java.util.Arrays;
import javax.servlet.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import com.humanbizz.web.security.UserInfoTokenServices;
#Configuration
#EnableWebSecurity
#EnableOAuth2Client
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private OAuth2ClientContextFilter oauth2ClientContextFilter;
#Autowired
OAuth2ClientContext oauth2ClientContext;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login*", "/forgot-password*", "/signup**", "/signup/**", "/resources/**", "/403", "/storage/api/download/**", "/test/public/**").permitAll()
.antMatchers("/user**").anonymous()
.anyRequest().authenticated()
.and()
.exceptionHandling().accessDeniedPage("/403")
.and()
.exceptionHandling()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("?")
.usernameParameter("username")
.passwordParameter("password")
.defaultSuccessUrl("/")
.failureUrl("/login?error=true")
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.logout().logoutSuccessUrl("/login").deleteCookies("JSESSIONID")
.and()
.addFilterBefore( myFilter(), BasicAuthenticationFilter.class);
}
private Filter myFilter() throws Exception{
OAuth2ClientAuthenticationProcessingFilter myFilter = new OAuth2ClientAuthenticationProcessingFilter("/login");
OAuth2RestTemplate myTemplate = new OAuth2RestTemplate(template(), oauth2ClientContext);
teodeskFilter.setRestTemplate(myTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices("http://localhost:9000/user", "acme");
tokenServices.setRestTemplate(myTemplate);
teodeskFilter.setTokenServices(tokenServices);
return myFilter;
}
#Bean
public OAuth2ProtectedResourceDetails template() {
AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
details.setClientId("acme");
details.setClientSecret("acmesecret");
details.setAccessTokenUri("http://localhost:9000/oauth/token"); details.setUserAuthorizationUri("http://localhost:9000/oauth/authorize");
details.setGrantType("password");
details.setScope(Arrays.asList("read"));
return details;
}
}
My question is how to configure filter to properly obtain token using form and password grunt type. Form is located on web application and should make request to remote auth server.The examples I have encountered are mostly related to Spring Boot or are solved by the fact that both Authorization Server and Resource Server were together on the same application.
I am stuck configuring Spring Error mapping with Spring security in Spring Boot 1.3.5 app.
I have follow security config class:
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.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("123").roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/admin").hasRole("ADMIN").and()
.csrf().disable();
}
}
And ExceptionController :
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
#Controller
public class ExceptionController implements ErrorController {
private static final String ERROR_PATH = "/error";
#RequestMapping(value = ERROR_PATH)
#ResponseStatus(HttpStatus.NOT_FOUND)
public String error(HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
return "redirect:/";
}
#Override
public String getErrorPath() {
return ERROR_PATH;
}
}
/admin secure page works fine without ExceptionController . But when I adding it, login form not appearing, I have tried a lot of things, such as ControllerAdvice, but nothing seems work for me. What's proper solution here ?