Spring Security And Angular 6 HTTPS requests - java

my backend app in spring boot and secured with ssl. I used OAuth2 facebook login. Also the frontend app in Angular 7 and secured by ssl. My problem is sending requests Angular to my Spring boot App. All apps is https.
P.S. All works if i add url to webSecurity.ignoring(). and not secure my backend. i think some problem with security and HTTPS requests. THANKS FOR HELP.
BACKEND
SecurityConfig.java
#RestController
#CrossOrigin(origins = "https://192.168.1.106:4400")
#Configuration
#Order(1000)
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
UserRepo userRepo;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/unauth/**").permitAll()
.antMatchers(HttpMethod.POST, "/unauth/upload").permitAll()
.antMatchers(HttpMethod.POST, "/api/**").authenticated()
.antMatchers(HttpMethod.PUT, "/api/**").authenticated()
.antMatchers(HttpMethod.DELETE, "/api/**").authenticated()
.antMatchers(HttpMethod.GET, "/api/**").authenticated()
.anyRequest().permitAll()
.and().logout().logoutSuccessUrl("/").permitAll();
}
#Override
public void configure(WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers(HttpMethod.GET, "/unauth/**");
webSecurity.ignoring().antMatchers(HttpMethod.POST, "/unauth/**");
}
webSecurity.ignoring().antMatchers(HttpMethod.POST, "/unauth/**");
}
SomeRestController.java
#RestController
#CrossOrigin(origins = "https://192.168.1.106:4400")
#RequestMapping ("/api")
public class ProductService {
#Autowired
private ProductRepo productRepo;
#CrossOrigin(origins = "https://192.168.1.106:4400")
#GetMapping("/products")
public List<Product> getProducts(){
return productRepo.findAll();
}
SpringBootApplication.java
#SpringBootApplication
#EnableOAuth2Sso
#CrossOrigin(origins = {"https://192.168.1.106:4400"}, allowCredentials = "false")
public class MongoTestApplication {
public static void main(String[] args) {
SpringApplication.run(MongoTestApplication.class, args);
}
}
FRONTEND
SomeComponent.html
< button (click)="makeRequest()"> MAKE REQUEST < /button >
SomeComponent.ts
val:any = {};
makeRequest(){
this.http.get("https://localhost:8443/api/products").subscribe(value => {this.val = value; console.log(this.val.key)});
}
ERROR
error in browser
Access to XMLHttpRequest at 'https://localhost:8443/api/brands' from origin 'https://192.168.1.106:4400' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
core.js.pre-build-optimizer.js:15714 ERROR n {headers: t, status: 0, statusText: "Unknown Error", url: "https://localhost:8443/api/brands", ok: false, …}

Edit your main class as below and remove all #CrossOrigin from the controllers.
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#SpringBootApplication
#EnableOAuth2Sso
public class MongoTestApplication {
public static void main(String[] args) {
SpringApplication.run(MongoTestApplication.class, args);
}
#SuppressWarnings("deprecation")
#Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "PUT", "POST", "DELETE", "OPTIONS");
}
};
}
}

Related

Config CORS in a client/server system with Spring Boot, Apache and Tomcat

I am developing a client-server architecture for the first time and I have some problems to configure the server to accept CORS.
I've read, searched and test a lot, but I can not make it work in my system, I do not know what is wrong.
I developed the client inAngular and the web service in Spring Boot 2.0.4 with Oauth2 security. On the server there are running an Apache that only accepts requests from port 443 to serve the web and redirect requests through port 8443 to the web service deployed in Tomcat 8.5 that is listening on port 8081.
<VirtualHost _default_:8443>
ProxyPass / http://localhost:8081/
ProxyPassReverse / http://localhost:8081/
DocumentRoot /var/www/html
...
Changes that I made in the Apache configuration
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "authorization"
</IfModule>
SecurityConfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private ClientDetailsService clientDetailsService;
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
return super.authenticationManagerBean();
}
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception
{
//#f:off
http.cors()
.and()
.csrf()
.disable()
.anonymous()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest()
.authenticated();
//#f:on
}
#Override
public void configure(WebSecurity web) throws Exception
{
super.configure(web);
web.ignoring()
.antMatchers("/v1/user/save")
.antMatchers("/v1/user/existsEMail")
.antMatchers("/v1/userAccess/existsUsername");
web.ignoring()
.antMatchers(HttpMethod.OPTIONS,"/**");
}
#Bean
public TokenStore tokenStore()
{
return new InMemoryTokenStore();
}
#Bean
#Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore)
{
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
#Bean
#Autowired
public ApprovalStore approvalStore(TokenStore tokenStore)
{
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
#Bean
public BCryptPasswordEncoder encoder()
{
BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom();
SecureRandom random = new SecureRandom(keyGenerator.generateKey());
return new BCryptPasswordEncoder(10, random);
}
#Bean
CorsConfigurationSource corsConfigurationSource()
{
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList(
HttpMethod.GET.name(),
HttpMethod.HEAD.name(),
HttpMethod.POST.name(),
HttpMethod.PUT.name(),
HttpMethod.DELETE.name()));
config.setAllowCredentials(true);
config.combine(config.applyPermitDefaultValues());
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
AuthorizationServerConfig
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter
{
#Autowired
private TokenStore tokenStore;
#Autowired
private UserAccessService userDetailsService;
#Autowired
private UserApprovalHandler userApprovalHandler;
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(ClientDetailsServiceConfigurer configurer) throws Exception
{
configurer.inMemory()
.withClient(SecurityConstant.CLIENT_ID)
.secret(SecurityConstant.CLIENT_SECRET)
.accessTokenValiditySeconds(SecurityConstant.ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(SecurityConstant.REFRESH_TOKEN_VALIDITY_SECONDS)
.scopes(SecurityConstant.SCOPE_READ, SecurityConstant.SCOPE_WRITE)
.authorizedGrantTypes(SecurityConstant.GRANT_TYPE_PASSWORD, SecurityConstant.REFRESH_TOKEN)
.resourceIds(SecurityConstant.RESOURCE_ID);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
{
endpoints.tokenStore(tokenStore)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.tokenEnhancer(new CustomTokenEnhancer());
endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
{
super.configure(security);
security.checkTokenAccess("permitAll()");
}
}
ResourceServerConfig
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter
{
#Autowired
private TokenStore tokenStore;
#Override
public void configure(ResourceServerSecurityConfigurer resources)
{
resources.tokenStore(tokenStore)
.resourceId(SecurityConstant.RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception
{
http.formLogin().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers(Uri.DIET + "/**").authenticated()
.anyRequest()
.authenticated()
.and()
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
And i getting an error message like this when i try to login in the web
Failed to load resource: the server responded with a status of 403 ()
Access to XMLHttpRequest at 'https://---.---.---:8443/folder/oauth/token' from origin 'https:// ---.---.---' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Are you sending the header "with credentials" on the client side? If it`s an angular 7 app you have to allow the with credentials header on the server side, adding on the cors configuration, and add an interceptor on the client side for every http client request. Besides that, you should not let "*" as allowed origins or the with credentials header will not work.
On Angular create this:
#Injectable()
export class CredentialsInterceptor implements HttpInterceptor {
constructor() {}
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
request = request = request.clone({
withCredentials: true
});
return next.handle(request);
}
}
And add to app.module:
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: CredentialsInterceptor,
multi: true
}
Another problem could be the order of the cors filter, it should be before the security filter on filterChain. You can handle it, with something like this:
#Bean
FilterRegistrationBean<CorsFilter> corsFilter(CorsConfigurationSource
corsConfigurationSource)
{
CorsFilter corsFilter = new CorsFilter(corsConfigurationSource);
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>
();
bean.setFilter(corsFilter);
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}

Spring security - implement oauth2 sso

I want to implement central authentication system with spring security and oauth2 sso. In other words, I have a spring boot application that is responsible for authorization and one simple client. My client has rest API. First I get token from the authorization server, then send a request to client API with an authorization header contains bearer token from above request. But this request always gets me server login page.
Here is the implementation of the server and the client:
Server
AuthorizationServerConfig.java
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("SampleClientId")
.secret("{noop}secret")
.authorizedGrantTypes("password")
.scopes("user_info")
.autoApprove(true);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(this.authenticationManager);
}
ApplicationConfig:
#SpringBootApplication
#EnableResourceServer
public class ApplicationConfig extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
}
SecurityConfig:
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//this is just example
auth.inMemoryAuthentication().withUser("user").password("{noop}1234").roles("user");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers("/login", "/oauth/authorize", "/oauth/token")
.and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
application.yml:
server:
port: 8900
servlet:
context-path: /auth
Client:
ApplicationConfig:
#SpringBootApplication
public class ApplicationConfig {
public static void main(String[] args) {
SpringApplication.run(ApplicationConfig.class, args);
}
}
SecurityConfig:
#Configuration
#EnableOAuth2Sso
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/login**")
.permitAll()
.anyRequest()
.authenticated();
}
}
TestController:
#RestController
public class HomeController {
#GetMapping("/")
public String index() {
return "home";
}
#RequestMapping("/admin")
public String admin() {
return "admin";
}
}
application.yml:
server:
port: 9000
servlet:
context-path: /client1
security:
basic:
enabled: false
oauth2:
client:
clientId: SampleClientId
clientSecret: secret
accessTokenUri: http://localhost:8900/auth/oauth/token
userAuthorizationUri: http://localhost:8900/auth/oauth/authorize
resource:
userInfoUri: http://localhost:8900/auth/user/me
First, I send client_id and secret code along side with username, password and grant_type to localhost:8900/auth/oauth/token and get a result like this:
{
"access_token": "603b505f-e701-43d0-b8b8-976a2178f7ea",
"token_type": "bearer",
"expires_in": 43199,
"scope": "user_info"
}
Now, I pickup above token and send a request to localhost:9000/client1/admin
with header contains above token. But it seems the client application ignores the header and shows server login page as result. How can I fix this problem?
#EnableOAuth2Sso is an annotation for using OAuth 2.0 as an end-user authentication mechanism (e.g. "A Login with Google" button). This annotation is wiring your app to redirect to a login page on your authorization server where you would log in and then get redirected back to your app.
If this is your intent, then you'll need to update your Authorization Server to support the authorization_code grant flow instead of the password grant flow.
However, if your client is strictly a REST API, then you are more likely to need to wire the client using #EnableResourceServer instead of #EnableOAuth2Sso. A Resource Server is what takes a token as authorization, via the Authorization HTTP header.

Enable SSO with Spring OAuth2 [duplicate]

This question already has an answer here:
Spring Security Authentication issue: HTTP 401
(1 answer)
Closed 4 years ago.
I'm trying to implement SSO using Spring OAuth lib for learning purpose.
The AuthenticationServer looks like this:
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory() //
.withClient("acme") //
.secret("acmesecret") //
.authorizedGrantTypes("authorization_code", "refresh_token", "password") //
.scopes("openid");
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
}
WebSecurity like this:
#Configuration
#EnableWebSecurity
public class AuthorizeUrlsSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean(name = BeanIds.AUTHENTICATION_MANAGER)
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").permitAll().and() //
.logout().and() //
.authorizeRequests().anyRequest().hasRole("USER");
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
and RestController:
#RestController
#EnableResourceServer
public class UserController {
#GetMapping("/user/me")
public Principal user(Principal principal) {
return principal;
}
}
The web application is kept minimal:
#SpringBootApplication
#EnableOAuth2Sso
public class WebApplication implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
public static void main(String[] args) {
SpringApplication.run(WebApplication.class, args);
}
}
application.yml:
spring:
thymeleaf:
cache: false
security:
basic:
enabled: false
oauth2:
client:
clientId: acme
clientSecret: acmesecret
accessTokenUri: http://localhost:9999/auth/oauth/token
userAuthorizationUri: http://localhost:9999/auth/oauth/authorize
resource:
userInfoUri: http://localhost:9999/auth/user/me
when I enter the URL localhost:8080 I should be redirect to the login (generated by spring?), but I get a 401 error.
2018-09-29 12:42:28.257 DEBUG 7677 --- [nio-9999-exec-2] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point
What am I missing?
Thank you!
You need to set web security configuration in the web application.
The reason why you get 401 is even the login url is not allowed to be connected by Spring Security.
So basically you need to add a java config like the following
#Configuration
#EnableOAuth2Sso
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
}
}
Hope this helps! Happy Coding :)

Spring Security disable rememberMe doesn't work

I have Spring Boot application. It is necessary to send Authorization header on every request otherwise deny access to resource.
But if I made request with this header once I can send requests without it and receive content of resource. Why? Where am I wrong in code?
Spring Security configuration:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.rememberMe().disable()
.csrf().disable()
.authorizeRequests().anyRequest().fullyAuthenticated().and()
.httpBasic().and()
.formLogin().disable()
.logout().disable();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("1").password("1").roles("USER");
}
}
Controller:
#RestController
public class FooController {
#RequestMapping("/foo")
public Bar bar() {
Bar bar = new Bar();
return bar;
}
}
http
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
Disable create session. Session Management

Spring security 401 Unauthorized on unsecured endpoint

I'm trying to configure Spring Security on a Spring Boot application as follows:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private RestAuthenticationEntryPoint unauthorizedHandler;
#Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
JwtAuthenticationFilter authenticationTokenFilter = new JwtAuthenticationFilter();
authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationTokenFilter;
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
//#formatter:off
httpSecurity
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(this.unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/login", "/singup", "/subscribers").permitAll()
.anyRequest().authenticated();
// Custom JWT based security filter
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
//#formatter:on
}
}
My unauthorizedHandler is:
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
#Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
Finally, the REST controller for /subscribers is:
#RestController
public class SubscriberRestController {
#Autowired
ISubscribersService subscribersService;
#RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.GET)
#ResponseBody
public Number subscriberCount() {
return subscribersService.subscribersCount();
}
#RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.POST)
public String subscriberPost(#RequestBody SubscriberDocument subscriberDocument) {
return subscribersService.subscribersInsert(subscriberDocument);
}
#RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {
return "This is a test";
}
}
I use postman to test endpoints and when I do a POST to "localhost:8080/subscribers", I get:
I want to have opened endpoints (/subscribers) without any security control or credentials check, endpoints for singup and login and secured endpoints for authenticated users.
Thanks! :)
Spring Boot was not applying the configuration because couldn't find it. On Application.java config package was not included with #ComponentScan anotation.
After some researching, here is solution:
#SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
#ComponentScan(basePackages = { PackageConstants.PACKAGE_CONTROLLERS_REST, PackageConstants.PACKAGE_SERVICES,
PackageConstants.PACKAGE_SERVICES_IMPL, PackageConstants.PACKAGE_MONGO_REPOSITORIES,
PackageConstants.PACKAGE_MONGO_REPOSITORIES_IMPL, PackageConstants.PACKAGE_UTILS })
public class Application {
// Clase principal que se ejecuta en el bootrun
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Main line is #SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) it tells not use Spring Boot Security AutoConfiguration configuration. It is not full answer, because now you have to tell Spring user your Spring Security configuration class. Also i advice you to create Initializer class with init Root Config Classes, ApplicationConfiguration using and refuse to use SpringBoot applications. Something like this:
ApplicationConfig:
#Configuration
#EnableWebMvc
#ComponentScan("com.trueport.*")
#PropertySource("classpath:app.properties")
public class ApplicationConfig extends WebMvcConfigurerAdapter {
....
}
ApplicationSecurityConfig:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
....
}
Initializer:
public class Initializer implements WebApplicationInitializer {
private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
....
DispatcherServlet dispatcherServlet = new DispatcherServlet(ctx);
dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
ctx.register(ApplicationConfig.class);
ServletRegistration.Dynamic servlet = servletContext.addServlet(DISPATCHER_SERVLET_NAME,
dispatcherServlet);
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(true);
}
}
You need to add the following to your configure method /error is the default fall back when error occurs to the application due to any exception and it is secured by default.
protected void configure(HttpSecurity httpSecurity) throws Exception {
//disable CRSF
httpSecurity
//no authentication needed for these context paths
.authorizeRequests()
.antMatchers("/error").permitAll()
.antMatchers("/error/**").permitAll()
.antMatchers("/your Urls that dosen't need security/**").permitAll()
Also the below code snippet
#Override
public void configure(WebSecurity webSecurity) throws Exception
{
webSecurity
.ignoring()
// All of Spring Security will ignore the requests
.antMatchers("/error/**")
}
Now you will not get 401 and get 500 exception with details when an exception occurred for permitAll Urls
If your application is simply saving APIs, and you have included dependency for spring security - for any other reason (Mine was to enables headers X-Frame and Content-Security-Policy), then by default Spring includes servlet filter for csrf protection. If you do not disable this, all requests fail with HTTP 401 error.
To disable it, You create a Configuration class extending WebSecurityConfigurerAdapter and annotated with EnableWebSecurity
#EnableWebSecurity
#Configuration
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable();
}
}
This article is worthy the read - very detailed.

Categories