Good morning,
I am developing a Spring boot (latest version) application, secured with Spring security (latest version).
I am trying to make a PUT request from a JSP page to an Spring REST endpoint which should only return a String object, in particular:
JSP code: inside a script i am making the following AJAX request
<!-- change event of batch status script -->
function changeEventStatus(idEvento, statoEvento) {
let data = {"id_evento": idEvento, "stato": statoEvento};
$.ajax({
url: 'http://localhost:8080/entsorgafin/events/api/cambiaStatoEvento',
type: 'PUT',
contentType: 'application/json',
data: JSON.stringify(data)
}).then(function (data) {
console.log("process terminated.");
console.log("data collected:");
console.log(data);
});
}
Controller code: the controller is annotated with #RestController and #CrossOrigin annotations to enable CORS requests and spring automatic management of rest requests
#PutMapping("/cambiaStatoEvento")
public String changeEventStatus(#RequestBody Evento evento)
{
logger.info("API CONTROLLER - changing the status of the event with ID " + evento.getId_evento());
//If the status status is not Risolto, the event will be taken in charge
if(! evento.getStato().equals("Risolto"))
{
logger.info("API CONTROLLER - status of event " + evento.getId_evento() + " changed to In Lavorazione");
eventoService.changeEventStatus(evento.getId_evento(), "In Lavorazione");
} else
{
logger.info("API CONTROLLER - status of event " + evento.getId_evento() + " changed to Risolto");
eventoService.changeEventStatus(evento.getId_evento(), "Risolto");
}
return "SUCCESS";
}
I checked with chrome devtools and the payload is correctly encoded and sent, but Spring boot log this when I make a request:
2021-01-18 17:18:00.822 DEBUG 15564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "FORWARD" dispatch for PUT "/accessDenied", parameters={}
2021-01-18 17:18:00.827 WARN 15564 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'PUT' not supported]
2021-01-18 17:18:00.828 DEBUG 15564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "FORWARD" dispatch, status 405
2021-01-18 17:18:00.829 DEBUG 15564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for PUT "/error", parameters={}
2021-01-18 17:18:00.830 DEBUG 15564 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2021-01-18 17:18:00.832 DEBUG 15564 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2021-01-18 17:18:00.832 DEBUG 15564 --- [nio-8080-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Mon Jan 18 17:18:00 CET 2021, status=405, error=Method Not Allowed, trace=org.springframe (truncated)...]
2021-01-18 17:18:00.833 DEBUG 15564 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 405
Having said this, I tried GET requests and works just fine as expected, whereas DELETE and POST requests do not work as PUT ones.
Just by reading logs I think is a Spring security problem, but I can't understand what problem I am facing, I read from the Spring documentation that CORS requests are automatically managed and nothing should be done, but it is obviously not working that way.
If someone could help with what I am missing or just point to some place I can find answers as I really do not know what could be wrong here, thanks in advance.
EDIT
Security configuration
package com.entsorgafin.sr002EagleCloud.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.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
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.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;
#SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{
//Dependency Injection
#Autowired
private PasswordEncoder passwordEncoder;
#Qualifier("securityUserDetailService")
#Autowired
private UserDetailsService userDetailsService;
/**
* Manages the encoder to save passwords in the DB
* not in plain text
*
* #return PasswordEncoder object
*/
#Bean
public PasswordEncoder passwordEncoder()
{
return new BCryptPasswordEncoder();
}
/**
* Manages the configuration of the Authentication manager with
* user credentials and roles.
* <p>
* The AuthenticationManager processes any authentication request.
*
* #param auth AuthenticationManagerBuilder object
*/
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
{
auth.authenticationProvider(authenticationProvider());
}
/**
* Manages the configuration for specific http request.
*
* #param http HttpSecurity request
* #throws Exception exception
*/
#Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
//configure security for pages
.antMatchers("/static/**").permitAll()
.antMatchers(new String[]{"/login", "/accessDenied"}).permitAll()
.antMatchers("/**").access("hasAnyRole('admin', 'operatore', 'ufficio tecnico', 'processista')")
.anyRequest().authenticated()
//creates login form
.and().formLogin().loginPage("/login").loginProcessingUrl("/login")
.defaultSuccessUrl("/home").failureUrl("/accessDenied")
.usernameParameter("id_utente").passwordParameter("password")
//catches exceptions http 403 response
.and().exceptionHandling().accessDeniedPage("/accessDenied");
http.requestCache().disable();
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
}
/**
* Manages the storage of user credentials inside database
*
* #return The authenticationProvider Object
*/
#Bean
public DaoAuthenticationProvider authenticationProvider()
{
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userDetailsService);
authenticationProvider.setPasswordEncoder(passwordEncoder);
return authenticationProvider;
}
#Bean
public AuthenticationTrustResolver getAuthenticationTrustResolver()
{
return new AuthenticationTrustResolverImpl();
}
}
Regarding csrf I added to the head the JSP meta tag <sec:csrfMetaTags/> which should take care of the csrf protection or at least the documentation says this.
EDIT 2
By changing the Ajax request as follows
<!-- change event of batch status script -->
function changeEventStatus(idEvento, statoEvento) {
let csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
let csrfToken = $("meta[name='_csrf']").attr("content");
let csrfHeader = $("meta[name='_csrf_header']").attr("content");
let data = {};
let headers = {};
data[csrfParameter] = csrfToken;
data["id_evento"] = idEvento;
data["stato"] = statoEvento;
headers[csrfHeader] = csrfToken;
$.ajax({
url: 'http://localhost:8080/entsorgafin/events/api/cambiaStatoEvento',
type: 'PUT',
headers: headers,
contentType: 'application/json',
data: JSON.stringify(data)
}).then(function (data) {
console.log("process terminated.");
console.log("data collected:");
console.log(data);
});
}
the request is performed correctly, now the problem is how to deal with the csrf token, as Spring tries to deserialize and put it into the java object (Evento in this case) and give back
Failed to evaluate Jackson deserialization for type [[simple type, class com.entsorgafin.sr002EagleCloud.model.Evento]]
Could not resolve parameter [0] in public java.lang.String com.entsorgafin.sr002EagleCloud.controller.rest.EventsController_rest.changeEventStatus(com.entsorgafin.sr002EagleCloud.model.Evento): Content type 'application/json;charset=UTF-8' not supported
Completed 415 UNSUPPORTED_MEDIA_TYPE
The payload of the request is:
{_csrf: "88c27418-7d48-4d76-a6ec-d76e7a45a61a", id_evento: 50, stato: "Attivo"}
How can i instruct spring boot not to use the csrf token for deserialization?
Related
I'm trying to create a simple spring boot app with spring security, with custom login form.
Issue:
The app directly opens the default login page instead of the custom login view & it could not resolve any of the other thymeleaf views too.
Directly accessing all other views (/home, /error) renders the error: This localhost page can't be found. Opening http://localhost:8080/login takes only to the default login page & not the custom one.
Note: The html templates are placed under /src/main/resources/templates folder - which is the default place springboot looks into.
The key thing here is that I am using the #EnableWebSecurity
annotation, with SecurityFilterChain bean (which is introduced in
Spring Security 5.4), like this:
#EnableWebSecurity
public class WebSecurityConfig {
#Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
...
}
instead of the more common (but, has been deprecated since Spring Security 5.7.0-M2) way of extending the
WebSecurityConfigurerAdapter class as below.
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
...
}
It seems the latter works fine without any issues.
Few of the solutions suggested in various forums - which I have already tried.
Keep the project structure in a way that all the other packages are placed under the base package (the one with the main class with #SprintBootApplication annotation).
Use #ComponentScan={<your_base_package>} - if packages are in the order mentioned in point 1. Or, #ComponentScan={<package-1>, <package-2>, etc}, if the packages are independent of each other.
Both the above solutions were suggested to avoid the 404 error & view not resolved issues.
Use #RestController instead of #Controller.
This was suggested both for WhiteLabel error, and when the view name is returned just as a string, instead of a view.
Keep the mapping url value in the controller methods (like, /login) & the the view name different. If the mapping url as /login, change the view name as loginpage.html (or, something different).
This was suggested for circular path issues - when resolving view names.
Some suggested using #RequestMapping("/login") at class-level, rather than method-level. Although, I didn't see any difference with either approach.
Note that all of the above are based on WebSecurityConfigurerAdapter & not on SecurityFilterChain.
The only references from the official documentation/blogs, that I
could find for this requirement (custom login with
SecurityFilterChain) were these two:
i.
https://docs.spring.io/spring-security/site/docs/4.1.3.RELEASE/guides/html5/form-javaconfig.html
ii.
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter
Unfortunately, performing the steps given there didn't get the result.
I think the below issue is the same (or, related) to this, but no
solution was given to that either.
https://github.com/spring-projects/spring-security/issues/10542
And, almost all the other git/blogs/websites/video references available, are
using the WebSecurityConfigurerAdapter class only.
Web Security Config class:
#EnableWebSecurity
public class WebSecurityConfig {
// #Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/home", "/login**","/callback/", "/webjars/**", "/css**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
// .loginPage("/loginpage")
.usernameParameter("email")
.passwordParameter("password")
.loginPage("/login").loginProcessingUrl("/login")
.permitAll()
.defaultSuccessUrl("/home")
.failureUrl("/login?message=error")
.and()
// .logout()
// .logoutUrl("/perform_logout")
// .logoutSuccessUrl("/login?message=logout");
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
.permitAll();
return http.build();
}
}
Login Controller:
(Leaving some of the commented code, to hint what else has been tried, so far).
At some point in time, the control entered into the login method & printed the model object's value (string). However, the login view still was not getting resolved & resulted in 404 error only.
//#RestController
#Controller
#ResponseBody
//#RequestMapping("/")
public class LoginController {
#GetMapping({"/", "/home"})
// public String home() {
// #GetMapping({"/", "/showHome"})
public ModelAndView home(ModelAndView mav) {
System.out.println("Inside GetMapping(/home) method of LoginController.");
mav.setViewName("home");
mav.addObject("Using #Controller and #ResponseBody, in the Controller");
System.out.println("View Object: " + mav.getView());
System.out.println("View Name: " + mav.getViewName());
System.out.println("mav.hasView(): " + mav.hasView());
return mav;
// return "home";
}
#GetMapping("/login-error")
// #GetMapping("/error")
#RequestMapping("/login")
public String login(HttpServletRequest request, Model model) {
HttpSession session = request.getSession(false);
String errorMessage = null;
if (session != null) {
AuthenticationException ex = (AuthenticationException) session
.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
if (ex != null) {
errorMessage = ex.getMessage();
}
}
System.out.println("--->" + errorMessage);
model.addAttribute("errorMessage", errorMessage);
return "login";
}
}
I added a main configuration for MVC too, although I believe these are the default configs which Springboot assumes itself & can work even without this.
Main Configuration class:
#Configuration
#ComponentScan("vlan.test.springboot.customLogin")
public class MainConfiguration implements WebMvcConfigurer {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/static/**", "classpath:/public/**", "classpath:/templates/**", "classpath:/resources/**"
};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
registry.addResourceHandler("/templates/**").addResourceLocations("/templates/");
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void addViewControllers(ViewControllerRegistry viewRegistry) {
viewRegistry.addViewController("/").setViewName("home");
viewRegistry.addViewController("/home").setViewName("home");
viewRegistry.addViewController("/login").setViewName("login");
}
}
Gradle build file:
implementation 'org.springframework.boot:spring-boot-devtools'<br/>
implementation 'org.springframework.boot:spring-boot-starter-web'<br/>
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'<br/>
implementation 'org.springframework.boot:spring-boot-starter-security'<br/>
implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'<br/>
implementation 'org.zalando:logbook-spring-boot-starter:2.14.0'
Project structure:
Extract from the logs - that I found relative/worth-noting.
Check the "..invalid session id..." and "..Failed to authorize filter invocation..." parts.
2022-08-18 12:09:43.297 INFO 16596 --- [http-nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 10 ms
2022-08-18 12:09:43.334 DEBUG 16596 --- [http-nio-8080-exec-1] o.s.security.web.FilterChainProxy : Securing GET /
2022-08-18 12:09:43.351 DEBUG 16596 --- [http-nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
2022-08-18 12:09:43.363 DEBUG 16596 --- [http-nio-8080-exec-1] ****o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext
2022-08-18 12:09:43.364 DEBUG 16596 --- [http-nio-8080-exec-1] o.s.s.w.session.SessionManagementFilter : Request requested invalid session id EF53E44688D581C69527A5442A987DB6
2022-08-18 12:09:43.394 DEBUG 16596 --- [http-nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [GET /] with attributes [authenticated]
2022-08-18 12:09:43.445 DEBUG 16596 --- [http-nio-8080-exec-1] o.s.s.w.s.HttpSessionRequestCache : Saved request http://localhost:8080/ to session****
2022-08-18 12:09:43.448 DEBUG 16596 --- [http-nio-8080-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using And [Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.HeaderContentNegotiationStrategy#51020050, matchingMediaTypes=[application/xhtml+xml, image/*, text/html, text/plain], useEquals=false, ignoredMediaTypes=[*/*]]]
2022-08-18 12:09:43.450 DEBUG 16596 --- [http-nio-8080-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint#416ee886
2022-08-18 12:09:43.454 DEBUG 16596 --- [http-nio-8080-exec-1] o.s.s.web.DefaultRedirectStrategy : Redirecting to http://localhost:8080/login
2022-08-18 12:09:43.459 DEBUG 16596 --- [http-nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2022-08-18 12:09:43.466 DEBUG 16596 --- [http-nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2022-08-18 12:09:43.466 DEBUG 16596 --- [http-nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
2022-08-18 12:09:43.487 DEBUG 16596 --- [http-nio-8080-exec-2] o.s.security.web.FilterChainProxy : Securing GET /login
Complete log here: https://codeshare.io/dwlLDK
(Seems it'd live for only 24 hrs. Pls. let me know if you couldn't access it).
Edit(2022-08-22):
An excerpt from the application.properties file (just the thymeleaf & security config) - which is the reason for the issue (as explained in the accepted [self-identified] answer).
# thymeLeaf
spring.thymeleaf.enabled=true
spring.thymeleaf.cache=false
spring.thymeleaf.check-template=true
spring.thymeleaf.check-template-location=true
spring.thymeleaf.prefix=classpath:/templates
spring.thymeleaf.suffix=.html
#security
server.error.whitelabel.enabled=false
I have an example Spring Boot application here:
https://github.com/Aliuken/JobVacanciesApp_Java11
Hope that it helps.
I fixed the issue myself.
(Adding it as an accepted answer, so that it's easy for people who stumble upon this page.)
The actual issue was a missing trailing / in the thymeleaf prefix config, in the application.properties file:
spring.thymeleaf.prefix=classpath:/templates.
This should have been spring.thymeleaf.prefix=classpath:/templates/.
Once I added it, it started recognizing the templates (including the custom login template/view).
I am trying to setup Resource Server to validate jwt tokens with Authentication server by using NimbusJwtDecoder.withJwkSetUri
Following is my configuration in Resource server
#Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.oauth2ResourceServer(c -> {
c.jwt(j -> {
j.decoder(jwtDecoder());
});
});
http.authorizeRequests().anyRequest().authenticated();
}
#Bean
public JwtDecoder jwtDecoder(){
RestTemplate rest = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = rest.getInterceptors();
interceptors.add(new BasicAuthenticationInterceptor("client1","secret1"));
interceptors.add(new LoggingInterceptor());
rest.setInterceptors(interceptors);
return NimbusJwtDecoder.withJwkSetUri("http://localhost:8080/oauth/token_key").restOperations(rest).build();
}
}
And I have simple endpoint in Resource server to test
#RestController
public class HelloController {
#GetMapping("/hello")
public String hello(){
return "Hello";
}
}
However when I access "/hello" with access token already got from auth server then I get unauthorised response and observe following logs in Resource server.
Response body: {"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8ieQxTVHq4jBSM3JpO7UcFOa5UrorX5KhRbMqEtT746yGTqqv+t1EW6l8G31bGc6G/IHy7032vpKNxAgLVcoCrdoOakbGLb1y2+ElB9QmEEEplARWLQ43t47ywd0UA7MhF9WIbud1Z6kqySrsrBTzjPu+fwCElzUFveyaiPsZDlrEAU6yMLQ23nEP3bBCgDtGMVs1a7RsmAzfUsruelqNaAQQamobkjEMWB8ewZWjtsriIldNjGEAUznw4bcJ963ExtmgfMAHS7XhuWqu58yIzdBopxhZvt/falc5cyp7OCP1ZPEjkHJ5TikJksqOgDgWhiIVtr/3cUjd8vnX4y4QIDAQAB\n-----END PUBLIC KEY-----"}
2021-05-15 11:54:47.468 DEBUG 40223 --- [nio-9090-exec-3] o.s.web.client.RestTemplate : Response 200 OK
2021-05-15 11:54:47.468 DEBUG 40223 --- [nio-9090-exec-3] o.s.s.o.s.r.a.JwtAuthenticationProvider : Failed to authenticate since the JWT was invalid
2021-05-15 11:54:47.469 DEBUG 40223 --- [nio-9090-exec-3] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-05-15 11:54:47.469 DEBUG 40223 --- [nio-9090-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
It seems auth server was able to provide public key successfully but resource server could not use this public key to validate provided jwt token.
Any help is highly appreciated.
Hi please add class #EnableAuthorizationServer anotation but not working please read this Outh2 documentation https://projects.spring.io/spring-security-oauth/docs/oauth2.html
I am using Spring-boot config for basic-auth and when I am trying to access the http://192.168.0.3/v1 using credentials, I am getting CORS error, even though I have configurations for CORS.
The weird thing is, when I am accessing the http://192.168.0.3/v1/signup, I am able to create a user.
why CORS error for the root url access only?
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
#ComponentScan(basePackages = { "com.ofloy.rest.security" })
#Import({CorsConfig.class})
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/signup/**").permitAll()
.anyRequest().authenticated()
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().csrf().disable()
;
}
}
#Configuration
public class CorsConfig {
#Bean
public FilterRegistrationBean<Filter> customCorsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<Filter>(new CorsFilter(source));
bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
return bean;
}
}
I am using UserDetailsService for querying the real user from my DB and set server.servlet.context-path = /v1/
Basically two issues I am facing with the above configuration:
I am able to access http://192.168.0.3/v1/signup but not
http://192.168.0.3/v1/ from the broweser, as getting CORS error.
Accessing http://192.168.0.3/v1(from POSTMAN) using the credentials to check if
the credentials are correct, give me the 404 error. 404 if
credentials are correct and 401 is not correct. Why 404?
Note: One thing I have noticed for second issues is, even if I send the POST request to http://192.168.0.3/v1, the spring Logs shows it GET request, here is the log stack.
DEBUG DispatcherServlet : GET "/v1/", parameters={}
WARN PageNotFound : No mapping for GET /v1/
DEBUG DispatcherServlet : Completed 404 NOT_FOUND
DEBUG DispatcherServlet : "ERROR" dispatch for GET "/v1/error", parameters={}
DEBUG RequestMappingHandlerMapping : Mapped to public
org.springframework.http.ResponseEntity org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
DEBUG HttpEntityMethodProcessor : Using 'application/json', given
[/] and supported [application/json, application/*+json]
DEBUG HttpEntityMethodProcessor : Writing [{timestamp=Wed Jan 30 16:16:40 IST 2019, status=404, error=Not Found, message=No message available,
path=/v1/}]
DEBUG DispatcherServlet : Exiting from "ERROR" dispatch, status 404
UPDATE: this is the CORS error in browser
Access to XMLHttpRequest at 'http://192.168.43.70:8085/v1' from
origin 'http://localhost:3007' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
Redirect is not allowed for a preflight request.
I would do something like below on the controller which handles the request:
#CrossOrigin(origins = "http://localhost:3007")
#RestController
#RequestMapping("/v1")
public class VoneController {
I'm using keycloak 3.4 and spring boot to develop a web app.
I'm using the Active Directory as User Federation to retrieve all users information.
But to use those information inside my web app I think I have to save them inside the "local-webapp" database.
So after the users are logged, how can I save them inside my database?
I'm thinking about a scenario like: "I have an object A which it refers to the user B, so I have to put a relation between them. So I add a foreign key."
In that case I need to have the user on my DB. no?
EDIT
To avoid to get save all users on my DB I'm trying to use the Administrator API, so I added the following code inside a controller.
I also created another client called Test to get all users, in this way I can use client-id and client-secret. Or is there a way to use the JWT to use the admin API?
The client:
Keycloak keycloak2 = KeycloakBuilder.builder()
.serverUrl("http://localhost:8080/auth/admin/realms/MYREALM/users")
.realm("MYREALMM")
.username("u.user")
.password("password")
.clientId("Test")
.clientSecret("cade3034-6ee1-4b18-8627-2df9a315cf3d")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(20).build())
.build();
RealmRepresentation realm2 = keycloak2.realm("MYREALMM").toRepresentation();
the error is:
2018-02-05 12:33:06.638 ERROR 16975 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.Error: Unresolved compilation problem:
The method realm(String) is undefined for the type AccessTokenResponse
] with root cause
java.lang.Error: Unresolved compilation problem:
The method realm(String) is undefined for the type AccessTokenResponse
Where am I doing wrong?
EDIT 2
I also tried this:
#Autowired
private HttpServletRequest request;
public ResponseEntity listUsers() {
KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) request.getUserPrincipal();
KeycloakPrincipal principal=(KeycloakPrincipal)token.getPrincipal();
KeycloakSecurityContext session = principal.getKeycloakSecurityContext();
Keycloak keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:8080/auth")
.realm("MYREALMM")
.authorization(session.getToken().getAuthorization().toString())
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(20).build())
.build();
RealmResource r = keycloak.realm("MYREALMM");
List<org.keycloak.representations.idm.UserRepresentation> list = keycloak.realm("MYREALMM").users().list();
return ResponseEntity.ok(list);
but the authorization is always null.
Why?
EDIT 3
Following you can find my spring security config:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled=true)
#ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
#KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.httpBasic().disable();
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/webjars/**").permitAll()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.logout()
.logoutUrl("/logout")
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
.permitAll()
.logoutSuccessUrl("/")
.invalidateHttpSession(true);
}
#Autowired
public KeycloakClientRequestFactory keycloakClientRequestFactory;
#Bean
public KeycloakRestTemplate keycloakRestTemplate() {
return new KeycloakRestTemplate(keycloakClientRequestFactory);
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper();
simpleAuthorityMapper.setPrefix("ROLE_");
simpleAuthorityMapper.setConvertToUpperCase(true);
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(simpleAuthorityMapper);
auth.authenticationProvider(keycloakAuthenticationProvider);
}
#Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/webjars/**");
}
#Bean
#Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken accessToken() {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request.getUserPrincipal()).getCredentials()).getToken();
}
}
EDIT 4
These are the properties inside the applicatoin.properties
#######################################
# KEYCLOAK #
#######################################
keycloak.auth-server-url=http://localhost:8181/auth
keycloak.realm=My Realm
keycloak.ssl-required=external
keycloak.resource=AuthServer
keycloak.credentials.jwt.client-key-password=keystorePwd
keycloak.credentials.jwt.client-keystore-file=keystore.jks
keycloak.credentials.jwt.client-keystore-password=keystorePwd
keycloak.credentials.jwt.alias=AuthServer
keycloak.credentials.jwt.token-expiration=10
keycloak.credentials.jwt.client-keystore-type=JKS
keycloak.use-resource-role-mappings=true
keycloak.confidential-port=0
keycloak.principal-attribute=preferred_username
EDIT 5.
This is my keycloak config:
the user that I'm using to login with view user permission:
EDIT 6
This the log form keycloak after enabling logging:
2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] o.k.adapters.PreAuthActionsHandler : adminRequest http://localhost:8080/utente/prova4
2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] .k.a.t.AbstractAuthenticatedActionsValve : AuthenticatedActionsValve.invoke /utente/prova4
2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler : AuthenticatedActionsValve.invoke http://localhost:8080/utente/prova4
2018-02-12 08:31:00.274 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler : Policy enforcement is disabled.
2018-02-12 08:31:00.275 3DEBUG 5802 --- [nio-8080-exec-1] o.k.adapters.PreAuthActionsHandler : adminRequest http://localhost:8080/utente/prova4
2018-02-12 08:31:00.275 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler : AuthenticatedActionsValve.invoke http://localhost:8080/utente/prova4
2018-02-12 08:31:00.275 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler : Policy enforcement is disabled.
2018-02-12 08:31:00.276 3DEBUG 5802 --- [nio-8080-exec-1] o.k.adapters.PreAuthActionsHandler : adminRequest http://localhost:8080/utente/prova4
2018-02-12 08:31:00.276 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler : AuthenticatedActionsValve.invoke http://localhost:8080/utente/prova4
2018-02-12 08:31:00.276 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.AuthenticatedActionsHandler : Policy enforcement is disabled.
2018-02-12 08:31:10.580 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.s.client.KeycloakRestTemplate : Created GET request for "http://localhost:8181/auth/admin/realms/My%20Realm%20name/users"
2018-02-12 08:31:10.580 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.s.client.KeycloakRestTemplate : Setting request Accept header to [application/json, application/*+json]
2018-02-12 08:31:10.592 3DEBUG 5802 --- [nio-8080-exec-1] o.k.a.s.client.KeycloakRestTemplate : GET request for "http://localhost:8181/auth/admin/realms/My%20Realm%20name/users" resulted in 401 (Unauthorized); invoking error handler
2018-02-12 08:31:10.595 ERROR 5802 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 401 Unauthorized] with root cause
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:85) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:707) ~[spring-web-4.3.13.RELEASE.jar:4.3.13.RELEASE]
In order to access the whole list of users, you must verify that the logged user contains at least the view-users role from the realm-management client, see this answer I wrote some time ago. Once the user has this role, the JWT she retrieves will cointain it.
As I can infer from your comments, you seem to lack some bases about the Authorization header. Once the user gets logged in, she gets the signed JWT from keycloak, so as every client in the realm can trust it, without the need to ask Keycloak. This JWT contains the access token, which is later on required in the Authorization header for each of user's request, prefixed by the Bearer keyword (see Token-Based Authentication in https://auth0.com/blog/cookies-vs-tokens-definitive-guide/).
So when user makes the request to your app in order to view the list of users, her access token containing the view-users role already goes into the request headers. Instead of having to parse it manually, create another request yourself to access the Keycloak user endpoint and attach it (as you seem to be doing with KeycloakBuilder), the Keycloak Spring Security adapter already provides a KeycloakRestTemplate class, which is able to perform a request to another service for the current user:
SecurityConfig.java
#Configuration
#EnableWebSecurity
#ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
...
#Autowired
public KeycloakClientRequestFactory keycloakClientRequestFactory;
#Bean
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public KeycloakRestTemplate keycloakRestTemplate() {
return new KeycloakRestTemplate(keycloakClientRequestFactory);
}
...
}
Note the scope for the template is PROTOTYPE, so Spring will use a different instance for each of the requests being made.
Then, autowire this template and use it to make requests:
#Service
public class UserRetrievalService{
#Autowired
private KeycloakRestTemplate keycloakRestTemplate;
public List<User> getUsers() {
ResponseEntity<User[]> response = keycloakRestTemplate.getForEntity(keycloakUserListEndpoint, User[].class);
return Arrays.asList(response.getBody());
}
}
You will need to implement your own User class which matches the JSON response returned by the keycloak server.
Note that, when user not allowed to access the list, a 403 response code is returned from the Keycloak server. You could even deny it before yourself, using some annotations like: #PreAuthorize("hasRole('VIEW_USERS')").
Last but not least, I think #dchrzascik's answer is well pointed. To sum up, I would say there's actually another way to avoid either retrieving the whole user list from the keycloak server each time or having your users stored in your app database: you could actually cache them, so as you could update that cache if you do user management from your app.
EDIT
I've implemented a sample project to show how to obtain the whole list of users, uploaded to Github. It is configured for a confidential client (when using a public client, the secret should be deleted from the application.properties).
See also:
https://github.com/keycloak/keycloak-documentation/blob/master/securing_apps/topics/oidc/java/spring-security-adapter.adoc
I suggest double checking if you really need to have your own user store. You should relay solely on Keycloak's users federation to avoid duplicating data and hence avoiding issues that comes with that. Among others, Keycloak is responsible for managing users and you should let it do its job.
Since you are using OIDC there are two things that you benefit from:
In the identity token that you get in form of JWT you have a "sub" field. This field uniquely identifies a user. From the OpenID Connect spec:
REQUIRED. Subject Identifier. A locally unique and never reassigned identifier within the Issuer for the End-User, which is intended to be consumed by the Client, e.g., 24400320 or AItOawmwtWwcT0k51BayewNvutrJUqsvl6qs7A4. It MUST NOT exceed 255 ASCII characters in length. The sub value is a case sensitive string.
In keycloak, "sub" is just a UUID. You can use this field to correlate your "object A" to "user B". In your DB this would be just a regular column, not a foreign key.
In Java, you can access this JWT data using security context. You can also take a look at keycloak's authz-springboot quickstart where it is shown how you can access KeycloakSecurityContext - from there you can get an IDToken which has a getSubject method.
Keycloak provides Admin REST API that has a users resource. This is OIDC supported API so you have to be properly authenticated. Using that API you can perform operations on users - including listing them. You can consume that API directly or through use of Java SDK: keycloak admin client.
In this scenario, you should use the JWT that you get from user in request. Using JWT you are sure that someone who is making a request can list all users in that realm. For instance, please consider following code:
#GetMapping("/users")
public List<UserRepresentation> check(HttpServletRequest request){
KeycloakSecurityContext context = (KeycloakSecurityContext) request.getAttribute(KeycloakSecurityContext.class.getName());
Keycloak keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:8080/auth")
.realm("example")
.authorization(context.getTokenString())
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(20).build())
.build();
List<UserRepresentation> list = keycloak.realm("example").users().list();
return list;
}
In that case we are using HttpServletRequest and token that it contains. We can get the same data through use of org.springframework.security.core.Authentication from spring security or directly getting an Authorization header. The thing is that KeycloakBuilder expects a string as a 'authorization', not an AccessToken - this is the reason why you have that error.
Please keep in mind that in order for this to work, user that is creating a requests, has to have a 'view-users' role from 'realm-management' client. You can assign that role to him in 'Role Mapping' tab for that user or some group to which he belongs.
Besides, you have to be properly authenticated to benefit from security context, otherwise you will get a null. Exemplary spring security keycloak configuration class is:
#Configuration
#EnableWebSecurity
#ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
#Bean
public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/api/users/*")
.hasRole("admin")
.anyRequest()
.permitAll();
}
}
I have problem with Spring REST oAuth2 configuration. Springs sees and map my URLs, but after oauth2 security check (successful) claims there is no URL to match. But I have no idea why, because Spring sees it on app initialisation.
I am able to properly authenticate with /oauth/token and generate token.
I am just unable to process requests which do not need authorization with token.
Spring 4.0.6, spring-security 3.2.4, Spring-security-oauth2 2.0.1
Logs from context initialisation
2014-08-29 08:56:26.415 [Scanner-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/api/users/{email}],methods=[PUT],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.concurrent.Callable<org.springframework.http.ResponseEntity> com.example.user.UserCommandsController.update(java.lang.String)
2014-08-29 08:56:26.416 [Scanner-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/api/users/{email}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.concurrent.Callable<org.springframework.http.ResponseEntity> com.example.user.UserCommandsController.delete(java.lang.String)
2014-08-29 08:56:26.416 [Scanner-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/api/users/logout],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.concurrent.Callable<org.springframework.http.ResponseEntity> com.example.user.UserCommandsController.logout()
2014-08-29 08:56:26.416 [Scanner-1] INFO o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/api/users],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.concurrent.Callable<org.springframework.http.ResponseEntity<java.lang.Void>> com.example.user.UserCommandsController.signup(java.lang.String,java.lang.String)
After sending request
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/api/users'; against '/api/users'
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /api/users; Attributes: [permitAll]
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.a.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#31b7d21c, returned: 1
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object
2014-08-29 09:00:58.654 [qtp1157726741-28] DEBUG o.s.s.web.FilterChainProxy - /api/users reached end of additional filter chain; proceeding with original chain
2014-08-29 09:00:58.655 [qtp1157726741-28] DEBUG o.s.w.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcher' processing POST request for [/api/users]
2014-08-29 09:00:58.655 [qtp1157726741-28] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Looking up handler method for path /api/users
2014-08-29 09:00:58.655 [qtp1157726741-28] DEBUG o.s.w.s.m.m.a.RequestMappingHandlerMapping - Did not find handler method for [/api/users]
2014-08-29 09:00:58.655 [qtp1157726741-28] DEBUG o.s.s.o.p.e.FrameworkEndpointHandlerMapping - Looking up handler method for path /api/users
2014-08-29 09:00:58.655 [qtp1157726741-28] DEBUG o.s.s.o.p.e.FrameworkEndpointHandlerMapping - Did not find handler method for [/api/users]
2014-08-29 09:00:58.655 [qtp1157726741-28] WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/api/users] in DispatcherServlet with name 'dispatcher'
And configuration
#Configuration
#EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId("sample-resource-id");
}
#Override
public void configure(final HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.requestMatchers()
.antMatchers(HttpMethod.POST, "/api/buildings/**")
.antMatchers(HttpMethod.DELETE, "/api/**")
.antMatchers(HttpMethod.PATCH, "/api/**")
.antMatchers(HttpMethod.PUT, "/api/**")
.and()
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/api/buildings/**").access("hasRole('ROLE_USER')")
.antMatchers(HttpMethod.DELETE, "/api/**").access("hasRole('ROLE_USER')")
.antMatchers(HttpMethod.PATCH, "/api/**").access("hasRole('ROLE_USER')")
.antMatchers(HttpMethod.PUT, "/api/**").access("hasRole('ROLE_USER')");
}
}
#Controller
#EnableWebSecurity
#Profile("default")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
/**
* By default all request need authentication. Only those which do not need it, shall be specified explicitly.
*/
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.csrf().disable();
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/buildings/**").permitAll()//to consider anonymous()
.antMatchers(HttpMethod.POST, "/api/users").permitAll()//to consider anonymous()
.antMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated();
}
#Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/app/**","/webjars/**", "/images/**", "/oauth/uncache_approvals", "/oauth/cache_approvals");
}
#Override
#Bean(name = "authenticationManagerBean")
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Part of user controller
#RestController
#RequestMapping("/api")
public class UserCommandsController {
private final UserService userService;
private AccountRecoveryMailer accountRecoveryMailer;
private MessageSource messageSource;
#Inject
public UserCommandsController(final UserService userService, final AccountRecoveryMailer accountRecoveryMailer,
final MessageSource messageSource) {
this.userService = userService;
this.accountRecoveryMailer = accountRecoveryMailer;
this.messageSource = messageSource;
}
#RequestMapping(value = "/users", method = RequestMethod.POST)
public Callable<ResponseEntity<Void>> signup(#RequestParam String email, #RequestParam String password) {
return () -> {
//do something
};
}
}
What I want to achieve is to secure all requests and only some of them make with free access (or maybe with only Authorization header to match client_id).
Here is solution for my problem. The root of this evil thing was beans initialisation, or better to say their scopes. BTW SSL isn't needed.
Wrong configuration below, do not blindly copy-paste.
I had two #ComponentScan classes.
#Configuration
#EnableWebMvc
#ComponentScan(basePackageClasses = Application.class,
excludeFilters = #Filter({RestController.class, Controller.class, Service.class, Repository.class, Configuration.class}))
class WebMvcConfig extends WebMvcConfigurationSupport {
//some code
}
#Configuration
#ComponentScan(basePackageClasses = Application.class)
class ApplicationConfig {
//some code
}
And mine WebAppInitialization code
#Order(2)
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ApplicationConfig.class, DataSourceConfig.class, SecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebMvcConfig.class};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
return new Filter[]{characterEncodingFilter};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setInitParameter("defaultHtmlEscape", "true");
registration.setInitParameter("spring.profiles.active", "default");
}
}
As you can see, entire components class path scanning with all type of beans would be initialized in getRootConfigClasses() method, and only part of beans would be initialized in getServletConfigClasses() method, due to WebMvcConfig.class and its exclusion of some bean types in component scanning. This shall be enough in my opinion for Spring, because beans from rootContext are available for servletContext. And was, but only for web app instantiation. Spring Security oAuth2 haven't seen controller mappings.
Solution to this problem was to get rid of component scanning in WebMvcConfig, and change getServletConfigClasses() method to this:
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ApplicationConfig.class, WebMvcConfig.class};
}
Thanks to eager caching of Spring beans, everything shall be fine.
You setup the server with oAuth2, that server can be accessed in secure fashion (https:) only.
If you need to provide non-secure(http:) service, you have to create another server.
Let consider that if your home's door has lock, and only the persons who have the key can enter your home, your home is secure.
If you add another door without lock to your home, your home becomes not-secure.
If you want to make door without lock, you should install that door to other hut for non-secure use.
Secure home, and non-secure hut.
These may be what you want to build on your server.