3
Edit02
Habilitei spring-security
in my project, and now every API needs authentication, perfect was what I needed.
But I want only one API not to need authentication. I tried to use
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/usuario/informacoes/**")
.permitAll()
but it doesn’t work and I keep getting:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
Researching found many articles, and the vast majority suggest in this way:
https://www.baeldung.com/spring-security-expressions
https://www.baeldung.com/security-none-filters-none-access-permitAll
https://docs.spring.io/spring-security/site/docs/current/reference/html/jc.html
I have the following code:
Websecurityconfigureradapter
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
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.builders.WebSecurity;
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;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
@EnableWebSecurity
@EnableAuthorizationServer
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
protected void configure(HttpSecurity http, WebSecurity web) throws Exception {
protected void configure(HttpSecurity http) throws Exception {
System.out.println("Chamou HttpSecurity");
http.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/usuario/informacoes/*")
.permitAll()
.anyRequest()
.authenticated();
}
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring().antMatchers("/favicon.ico");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
API
@RestController
@RequestMapping("/usuario")
@RequestMapping(value = "/informacoes/{id}", method = RequestMethod.GET)
public ResponseEntity<Object[]> informacoesUsuario(@Valid @PathVariable("id") Long id) throws Exception {
Object[] response = usuarioServices.informacoesUsuario(id);
return ResponseEntity.status(HttpStatus.OK).body(response);
}
Securitycorsfilter
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityCORSFilter implements Filter {
public void init(FilterConfig fc) throws ServletException {
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
System.out.println("Chamou SecurityCORSFilter");
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "authorization, Content-Type");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, resp);
}
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mfac</groupId>
<artifactId>mfac</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mfac</name>
<description>mfac - rest</description>
<properties>
<java.version>12</java.version>
</properties>
<dependencies>
<!-- Segurança | Início -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<!-- Segurança | Fim -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
The interesting thing is that if I do a Request, for any API, the console does not print Chamou HttpSecurity
it seems that the settings of WebSecurityConfigurerAdapter
are not being applied.
I updated the code, but it still doesn’t work. I put 2 console log (I updated the question) and it seems that the Websecurityconfigureradapter is not being called
– Dup
I believe it is due to Authorization and Resource Server settings, do you really need them at this time? You will keep Authorization and Resource together?
– nullptr
I created a gist of a project of mine that is working
– nullptr
Sorry I don’t understand, you’re referring to
SecurityCORSFilter
? If yes, I had to put because I was returning Cors errors, because of the OPTIONS that the browser sends, only solution I found, was putting theSecurityCORSFilter
– Dup
I’m checking the gist, thank you very much for your attention
– Dup
The Annotations
@EnableAuthorizationServer
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
only let them if in fact it will provide all the settings of Resource and Authorization server– nullptr
I removed the Annotations
@EnableAuthorizationServer
@EnableAuthorizationServer ``@EnableGlobalMethodSecurity(prePostEnabled = true)
, however now it does not recognize the API to grab the token, if I make a request to/oauth/token
he return metimestamp:"25/06/2019"
status:404
error:"Not Found"
message:"No message available"
path:"/oauth/token"
As I removed the Annotations, I need to do the API to get the Token manually ?– Dup
@Dup, so you are using the Authorization server below, as you were passing the token to the server after authorization?
– nullptr
There it is, after I took the notes the API from where I picked up the token apparently no longer exists, now I’m trying to create a
tokenServices
to be called on my APIoauth/token
but I’m not sure if that’s really what needs to be done.– Dup
No need, the Annotation
@EnableAuthorizationServer
that enables this. But you must configure how you validate the token again, by enabling the@EnableResourceServer
the server must validate the token through some configuration, you configured the token validation?– nullptr
I did not make any settings, all project settings this in question, I have nothing more than this. Would you have Discord ? I can show more details of the project by there, if you want to add me Dup #1537
– Dup
I will provide a functional example also using Authorization and Resource server settings
– nullptr
OK thank you very much
– Dup
I noticed that if you remove the note
@Order(Ordered.HIGHEST_PRECEDENCE)
classSecurityCORSFilter
theWebSecurityConfigurerAdapter
is called and printed on the consoleChamou HttpSecurity
, but instead, this makes me have problems with CORS OPTIONS in Request from different domains, as the classSecurityCORSFilter
is no longer called after the annotation is removed. Would there be any way to make the two Classes have effect on the application ? because I need both, one for CORS issues and one to free up access to an API without requiring authentication.– Dup
@Dup in reality you don’t need a filter to implement the CORS settings, you must use the class Corsconfigurationsource. I also added an example in the reply
– nullptr
I added the
@Bean CorsConfigurationSource
in theWebSecurityConfigurerAdapter
but keeps returning me errorOPTIONS http://192.168.25.26:8080/oauth/token?grant_type=password&scope=password&username=1&password=1 401
to solve this problem in my oldSecurityCORSFilter
I had the following codeif ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
 response.setStatus(HttpServletResponse.SC_OK);
 }
for when you have a request likeOPTIONS
return with theStatus 200 OK
. Now how can I get the same result using Corsconfigur.. ?– Dup
Change the Press
config.setAllowedMethods(Arrays.asList("*"));
and try again, the configuration is so even to work the CORS, it seems magical :)– nullptr
I changed, continues the same error, the interesting thing is that the Request I do is not printing
"Chamou HttpSecurity"
on the console, I get the impression that these settings are not being used.– Dup
Would you have any example, where the question of
OPTIONS CORS
and the settings ofWebSecurityConfigurerAdapter
is working because I believe I’m lost with these Annotations, which ones to use and if I need to configure them separately.– Dup
I haven’t been able to solve this problem, I haven’t found any article that shows how I can properly configure Spring classes.
– Dup
@Dup, I added more details to you
– nullptr
@Dup managed to solve his problem?
– nullptr
I’m still trying to, by converting your example to my use case, I believe it goes well, thank you very much for the help.
– Dup